2011-05-23 128 views
3

以下代码在访问最后一个像素(x = 255,y = 255)时总是在Fill方法中导致AccessViolationException。但是,如果我使用200x200这样的大小,它就可以工作。 512 x 512或1024 x 1024或其他幂级别的尺寸也是同样的问题(似乎可以在4x4,8x8 ...高达32 x 32的范围内正常工作)。任何想法,为什么这是?WriteableBitmap访问冲突问题

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; 
} 

回答

3

两个问题。 (1)假设bitsPerPixels与设置颜色时的int大小相同。 (2)为什么在计算偏移量时x乘以3?

如果bitsPerPixels是32;然后(1)是电流与由4.

品(2)应乘以x如果bitsPerPixels是24然后(1)应是

 *((byte *) pBadkBufferWithOffset + 0) = color.R; 
     *((byte *) pBadkBufferWithOffset + 1) = color.G; 
     *((byte *) pBadkBufferWithOffset + 2) = color.B; 
+0

(1)真正的问题,(2)是不。 –

+0

谢谢你,两个有效和优点。 (1)确实是我的问题,改变你的建议解决了我的问题。在我的情况下乘以3是可以的,因为我知道在PixelFormats.Bgr24的情况下BitsPerPixel将是24。谢谢! – slurmomatic