Silverlight 3 brings a new bitmap API that achieves the following three primary goals:
Create a bitmap from scratch, in pixels
Processing images loaded from the server or locally on the client
Partition rendering from the visual tree in place to achieve a screenshot-like feature (in addition, pre-rendering and caching elements can sometimes play a role in performance)
Create a bitmap from scratch
The key to creating a bitmap is the WriteableBitmap class under System.Windows.Media.Imaging. You can use this class to create a source that is preconfigured to a normal image element.
﹤Grid x:Name="LayoutRoot"﹥
﹤Image x:Name="MyBitmap"
Width="200"
Height="200" /﹥
﹤/Grid﹥
The following code provides some interesting graphical effects.
private void BuildBitmap()
{
const int imageWidth = 200;
const int imageHeight = 200;
WriteableBitmap b =
new WriteableBitmap(imageWidth, imageHeight,
PixelFormats.Bgr32);
b.Lock();
for (int x = 0; x ﹤ imageWidth; x++)
{
for (int y = 0; y ﹤ imageHeight; y++)
{
// generate a color in Pbgra32 format
byte[] components = new byte[4];
components[0] = (byte)(x % 255); // blue
components[1] = (byte)(y % 255); // green
components[2] = (byte)(x * y % 255); // red
components[3] = 0; // unused
// you could certainly do your own masking here
int pixelValue = BitConverter.ToInt32(components, 0);
// set the pixel value
b[y * imageWidth + x] = pixelValue;
}
}
b.Invalidate();
b.Unlock();
MyBitmap.Source = b;
}
The final finished product is as follows:
It is obvious that the above code has undergone four processes: locking, writing, invalidating, unlocking. This is required for WPF compatibility.
You can also modify an existing bitmap and render the bitmap's content control.