|Thursday, 31 December 2009|
Page 3 of 3
The backbuffer uses the pixel format you sepecified when creating the WriteableBitmap and there is a BackBufferStride property that you can use to create a suitable storage mapping function.
It is easy enough to add some methods to set and get pixels in a particular case by way of two new extension methods defined in a static class created just to host the extension methods:
public static class bitmapextensions
The setPixel method first checks that the x and y co-ordinates are in the correct range and that the format is Brga32 (you can extend the method to deal with other formats):
public static void setPixel(
It then gets the backbuffer details:
Then it computes the storage mapping function to access the pixel at that x,y location and stores the specified colour split into the four bytes corresponding to the pixel format:
Finally we mark the pixel dirty and unlock the WriteableBitmap:
The getPixel method is very similar, only it assembles and returns a Color struct:
public static Color getPixel(
Notice that as we are only accessing the bits and not changing them there is no need to lock or mark an area as dirty.
These two extension methods are easy to use but you might want to think about using more direct methods if you are going to manipulate a lot of pixels. Direct access via the Pixel property, and assigning pre-computed integer colour values, is always going to be faster than using general methods and objects.
With these extension methods defined we can now give an example of accessing pixels:
wbmap.setPixel(5,10 , Colors.Red);
Finally, as an example of a dynamic image, the following plots a range of colours which depend on the position of the pixel according to a simple formula:
private void button1_Click(
|Last Updated ( Friday, 19 March 2010 )|