2011-05-23 21 views
3

次のコードは、最後のピクセル(x = 255、y = 255)にアクセスしたときに常にFillメソッドでAccessViolationExceptionを発生させます。しかし、200x200などのサイズを使用すると動作します。 512 x 512または1024 x 1024または他の2のべき乗サイズで同じ問題(4 x 4、8 x 8 ... 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

2つの問題。

(1)色を設定するときに、bitsPerPixelsがintのサイズと同じであることを前提としています。

(2)なぜオフセットを計算するときにxに3を掛けていますか?

bitsPerPixelsが32の場合、次に、(1)電流であり、bitsPerPixelsが24である場合(2)それ以外の4

によってXを乗算しなければならないこと、次いで(1)

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

なければならない(1)、本当の問題である(2)でありますない。 –

+0

ありがとう、2つの有効かつ良い点。 (1)は本当に私の問題であり、それをあなたの提案に変えて私の問題を解決しました。 PixelFormats.Bgr24の場合、BitsPerPixelは24になることがわかっているので、3で乗算するのは私の場合は問題ありません。ありがとうございました! – slurmomatic

関連する問題