WriteableBitmap访问冲突问题
当访问最后一个像素 (x = 255, y = 255) 时,以下代码始终会在 Fill 方法中引发 AccessViolationException。但是,如果我使用 200x200 这样的尺寸,它就可以工作。 512 x 512 或 1024 x 1024 或其他二次方尺寸也存在同样的问题(似乎适用于 4x4、8x8 ... 高达 32 x 32)。有什么想法吗?
var wb = new WriteableBitmap(256, 256, 96, 96, PixelFormats.Bgr24, null);
wb.Fill(256, 256, 3, Colors.Black);
...
public static void Fill(this WriteableBitmap bmp, int width, int height, int bytesPerPixel, Color color)
{
var rect = new Int32Rect(0, 0, width, height);
var fillColor = color.ToInt();
bmp.Lock();
unsafe
{
int pBackBuffer = (int)bmp.BackBuffer;
int stride = bmp.BackBufferStride;
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
int offset = y * stride + x * bytesPerPixel;
int pBackBufferWithOffset = pBackBuffer + offset;
*((int*) pBackBufferWithOffset) = fillColor;
}
}
bmp.AddDirtyRect(rect);
bmp.Unlock();
}
private static int ToInt(this Color color)
{
int c = color.R << 16; // R
c |= color.G << 8; // G
c |= color.B << 0; // B
return c;
}
The following code always causes an AccessViolationException in the Fill method when the last pixel (x = 255, y = 255) is accessed. However, if I use a size such as 200x200 it works. Same problem with 512 x 512 or 1024 x 1024 or other power-of-two sizes (seems to work fine with 4x4, 8x8 ... up to 32 x 32). Any ideas why that is?
var wb = new WriteableBitmap(256, 256, 96, 96, PixelFormats.Bgr24, null);
wb.Fill(256, 256, 3, Colors.Black);
...
public static void Fill(this WriteableBitmap bmp, int width, int height, int bytesPerPixel, Color color)
{
var rect = new Int32Rect(0, 0, width, height);
var fillColor = color.ToInt();
bmp.Lock();
unsafe
{
int pBackBuffer = (int)bmp.BackBuffer;
int stride = bmp.BackBufferStride;
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
int offset = y * stride + x * bytesPerPixel;
int pBackBufferWithOffset = pBackBuffer + offset;
*((int*) pBackBufferWithOffset) = fillColor;
}
}
bmp.AddDirtyRect(rect);
bmp.Unlock();
}
private static int ToInt(this Color color)
{
int c = color.R << 16; // R
c |= color.G << 8; // G
c |= color.B << 0; // B
return c;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
两个问题。
(1) 您假设设置颜色时,bitsPerPixels 与 int 的大小相同。
(2) 计算偏移量时为什么要将 x 乘以 3?
如果bitsPerPixels为32;则 (1) 为当前值,(2) 应将 x 乘以 4。
否则,如果 bitsPerPixels 为 24,则 (1) 应为
Two issues.
(1) Your are assuming that bitsPerPixels is the same as the size of an int when you set the color.
(2) Why are you multiplying x by 3 when calculting the offset?
If bitsPerPixels is 32; then (1) is current and (2) should be multiplying x by 4.
Else if bitsPerPixels is 24 then (1) should be