Recording issue with access to write access

The following code always raises an AccessViolationException in the Fill method when the last pixel is accessed (x = 255, y = 255). However, if I use a size like 200x200, it works. Same problem with 512 x 512 or 1024 x 1024 or other two-two sizes (it seems to work fine with 4x4, 8x8 ... up to 32 x 32). Any ideas why this 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;
}
+3
source share
1 answer

Two questions.

(1) Assume that the BitPixels match the int size when adjusting the color.

(2) Why do you multiply x by 3 when calculating the offset?

If the PerPixels bit is 32; then (1) is current and (2) multiply x by 4.

If the bitsPerPixels bit is 24, then (1) should be

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

All Articles