Silverlight 3 這次帶來的全新位元影像API實現了如下的三個首要目標:
◆從無到有建立位元影像,以像素為單位
◆在用戶端處理從伺服器或本地載入的映像
◆從視覺樹到位元影像的分區渲染,以達成類似於截屏的功能(另外,預渲染和緩衝元素有時也能起到提 高效能的作用)
從無到有建立位元影像
建立位元影像的關鍵在於System.Windows.Media.Imaging下的WriteableBitmap類。運用此類可以建立一個 預先分配到普通映像元素上的源。
﹤Grid x:Name="LayoutRoot"﹥
﹤Image x:Name="MyBitmap"
Width="200"
Height="200" /﹥
﹤/Grid﹥
以下提供的代碼可以實現一些很有趣的圖形效果。
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;
}
最終成品如下:
可以明顯看出,以上代碼經曆了四個流程:鎖定,寫入,無效化,解鎖。這是WPF相容所需要的。
你也可以修改一個現有的位元影像,並渲染該位元影像的內容控制項。