Calling the WriteableBitmap.WritePixels method
I'm trying to call the WriteableBitmap.WritePixels method, but I can't seem to understand the parameters. The MSDN article is very dull (Or shuold I say... null?), and I couldn't understand how to use the method.
Edit: I tried to modify a code from this article: http开发者_开发百科://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap%28v=VS.90%29.aspx
PixelFormat pf = PixelFormats.Rgba128Float;
WriteableBitmap wb = new WriteableBitmap(width * 5, height * 5, 100, 100, pf, new BitmapPalette(new List<Color> { Color.FromArgb(255, 255, 0, 0) }));
byte[] ColorData = { 0, 0, 0, 0 };
wb.WritePixels(new Int32Rect(0, 0, 1, 1), ColorData, 4, 0);
Background.Source = wb;
In the line before the last line the debugger claims that the buffer (ColorData) size is not sufficient.
Edit2: I tried again:
void RefreshGraphics()
{
PixelFormat pf = PixelFormats.Pbgra32;
WriteableBitmap wb = new WriteableBitmap(width * 5, height * 5, 100, 100, pf, new BitmapPalette(new List<Color> { Color.FromArgb(255, 255, 0, 0) }));
byte[] ColorData = new byte[1000];
byte t = 0;
for (int i = 0; i < 1000; i++)
ColorData[i] = t++;
wb.WritePixels(new Int32Rect(0, 0, 10, 10), ColorData, 10, 0);
Background.Source = wb;
}
Now a "Value is is not in the expected range." The stackTrace doesn't tell which one...
Edit 3: Problem Solved! Don't know how or why, but the code works (And I afraid to change it...)
Here's the way I understand it:
- System.Windows.Int32Rect sourceRect: The most obvious argument. Represents the position, width and height of the subset of your bitmap you are trying to write into.
- System.Array pixels: A one or two dimensional array of bytes. The pixel format you used in the bitmap constructor will determine how many byte entries are used for each pixel.
- System.Int32 stride: Defines how many of the pixels array entry should each row use (the width)
- System.Int32 offset: An offset in your input pixels array, if you want to reuse your array for more than one WritePixels call.
This article (for .NET 3) has some comments in the examples that help explain what the different parameters are (concepts like "stride") and how to calculate them. Scroll to the bottom where the actual code examples are. I'm not sure why they dumped those comments out of the .NET 4 version.
Edit: Can you share what your goal is with WritePixels? If you're trying to draw images, shapes, etc, I usually use DrawingContext to write to the bitmap and then Render it to a DrawingVisual instead.
Check the values of height and width. Perhaps the byte array is simply not big enough!
精彩评论