【IT168 技术】本文主要从四个方面来进行来介绍Silverlight 3 在Graphics方面的新特性。如何利用新的Bitmap API来创建我们自己的图像;透视3D图像(Perspective 3D Graphic) ;像素模糊和投影效果 以及Element-To-Element Binding。
Bitmap API的写图像功能:
新版的Bitmap API支持从写每个像素的值来创建自己的图像。这个用来支持生成Bitmap的类叫做WriteableBitmap,继承自BitmapSource类。这个类位于System.Windows.Media.Imaging名字空间中,其函数成员包括:
1: public sealed class WriteableBitmap : BitmapSource
2: {
3: public WriteableBitmap(BitmapSource source);
4: public WriteableBitmap(int pixelWidth, int pixelHeight, PixelFormat format);
5: public int this[int index] { get; set; }
6: public void Invalidate();
7: public void Lock();
8: public void Render(UIElement element, Transform transform);
9: public void Unlock();
10: }
可以看出我们可以通过两种形式来实例化这个WriteableBitmap。一个是通过传入已经初始化了的BitmapSource,另外一个是通过输入图像高度和宽度以及像素类型(有Bgr32和Pbgra32两种,后面一种可以创建半透明图像)。第5行的索引this[int index]可以用来读或取像素点。
写一个WriteableBitmap的流程是这样的。实例化WriteableBitmap,调用Lock方法,写像素点,调用Invalidate方法,最后是调用Unlock方式来释放所有的Buffer并准备显示。
如下文所示以描点的方式构建了整个Bgr32图像
1: private WriteableBitmap BuildTheImage(int width, int height)
2: {
3: WriteableBitmap wBitmap=new WriteableBitmap(width,height,PixelFormats.Bgr32);
4: wBitmap.Lock();
5:
6: for (int x = 0; x < width; x++)
7: {
8: for (int y = 0; y < height; y++)
9: {
10: byte[] brg = new byte[4];
11: brg[0]=(byte)(Math.Pow(x,2) % 255); //Blue, B
12: brg[1] = (byte)(Math.Pow(y,2) % 255); //Green, G
13: brg[2] = (byte)((Math.Pow(x, 2) + Math.Pow(y, 2)) % 255); //Red, R
14: brg[3] = 0;
15:
16: int pixel = BitConverter.ToInt32(brg, 0);
17:
18: wBitmap[y * height + x] = pixel;
19: }
20: }
21:
22: wBitmap.Invalidate();
23: wBitmap.Unlock();
24:
25: return wBitmap;
26: }
2: {
3: WriteableBitmap wBitmap=new WriteableBitmap(width,height,PixelFormats.Bgr32);
4: wBitmap.Lock();
5:
6: for (int x = 0; x < width; x++)
7: {
8: for (int y = 0; y < height; y++)
9: {
10: byte[] brg = new byte[4];
11: brg[0]=(byte)(Math.Pow(x,2) % 255); //Blue, B
12: brg[1] = (byte)(Math.Pow(y,2) % 255); //Green, G
13: brg[2] = (byte)((Math.Pow(x, 2) + Math.Pow(y, 2)) % 255); //Red, R
14: brg[3] = 0;
15:
16: int pixel = BitConverter.ToInt32(brg, 0);
17:
18: wBitmap[y * height + x] = pixel;
19: }
20: }
21:
22: wBitmap.Invalidate();
23: wBitmap.Unlock();
24:
25: return wBitmap;
26: }
画出来的图像如下图所示

图1 Bgr32图像
很神奇的一个改进。有了这个类,我们就可以操纵像素点了。在微软上对图像处理做些应用,比如去红点等功能。