To implement a writable bitmap with the Silverlight 3 bitmap API

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.