Over a million developers have joined DZone.

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.

 

Topics:

Published at DZone with permission of Rene Schulte. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}