WriteableBitmap Extension Methods
Bill Reiss (@billreiss) wrote a good blog post about the pixel format of the Silverlight 3 WriteableBitmap
class and included some nice helper methods for the pixel manipulation.
I used his two methods, optimized them a bit and packed them into a
static class as extension methods of the WriteableBitmap. I also added
some methods, which take the System.Windows.Media.Color structure as input parameter instead of bytes.
The SetPixeli
overloads of the methods use the precalculated index and don't
calculate the index position itself in every call and are therefore
faster.
The signature of the methods:
SetPixeli(this WriteableBitmap bmp, int index, byte r, byte g, byte b);
SetPixel(this WriteableBitmap bmp, int x, int y, byte r, byte g, byte b);
SetPixeli(this WriteableBitmap bmp, int index, byte a, byte r, byte g, byte b);
SetPixel(this WriteableBitmap bmp, int x, int y, byte a, byte r, byte g, byte b);
SetPixeli(this WriteableBitmap bmp, int index, Color color);
SetPixel(this WriteableBitmap bmp, int x, int y, Color color);
SetPixeli(this WriteableBitmap bmp, int index, byte a, Color color);
SetPixel(this WriteableBitmap bmp, int x, int y, byte a, Color color);
Usage:
int index = 0;
for (int y = 0; y < writeableBmp.PixelHeight; y++)
{
for (int x = 0; x < writeableBmp.PixelWidth; x++)
{
byte alpha = (byte)(x * x + y * y);
writeableBmp.SetPixeli(index++, alpha, Colors.Black);
}
}
writeableBmp.Invalidate();
The index position isn't calculated with x * writeableBmp.PixelWidth +
y in every iteration, instead I use an extra index variable. The
incrementation is a lightweight computational operation compared to the
multiplication + addition.
This short code snippet produces the image you can see above. It's really simple algorithmic beauty from the alpha channel.
Source code
You can download the WriteableBitmapExtensions class here.
Update:
The complete Visual Studio 2008 solution is also available for download.
| Attachment | Size |
|---|---|
| WriteableBitmapExtensions.zip | 1.53 KB |
| WriteableBmpSample.zip | 21.11 KB |
- Login or register to post comments
- 504 reads
- Printer-friendly version
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)









