问题描述
|
当访问最后一个像素(x = 255,y = 255)时,以下代码始终在Fill方法中导致AccessViolationException。但是,如果我使用200x200之类的尺寸,则可以使用。 512 x 512或1024 x 1024或其他2的幂次幂也存在相同的问题(似乎可以在4x4、8x8 ...最高32 x 32的情况下正常工作)。有什么想法吗?
var wb = new WriteableBitmap(256,256,96,PixelFormats.Bgr24,null);
wb.Fill(256,3,Colors.Black);
...
public static void Fill(this WriteableBitmap bmp,int width,int height,int bytesPerPixel,Color color)
{
var rect = new Int32Rect(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;
}
解决方法
两个问题。
(1)您假设在设置颜色时bitsPerPixels与int的大小相同。
(2)为什么在计算偏移量时将x乘以3?
如果bitsPerPixels为32;那么(1)是当前的(2)应该将x乘以4。
否则,如果bitsPerPixels为24,则(1)应该为
*((byte *) pBadkBufferWithOffset + 0) = color.R;
*((byte *) pBadkBufferWithOffset + 1) = color.G;
*((byte *) pBadkBufferWithOffset + 2) = color.B;