Silverlight寫圖像功能特點詳解
Silverlight對于圖像的處理是比較強大的。主要可以通過Bitmap API來實現Silverlight寫圖像。在這里我們將會為大家詳細介紹這一功能的實現方式,希望能對大家有所幫助,提高編程效率。#t#
新版的Bitmap API支持從寫每個像素的值來創(chuàng)建自己的圖像。這個用來支持生成Bitmap的類叫做WriteableBitmap,繼承自BitmapSource類。這個類位于System.Windows.Media.Imaging名字空間中,其函數成員包括:
- public sealed class WriteableBitmap
: BitmapSource - {
- public WriteableBitmap(BitmapSource source);
- public WriteableBitmap(int pixelWidth,
int pixelHeight, PixelFormat format); - public int this[int index] { get; set; }
- public void Invalidate();
- public void Lock();
- public void Render(UIElement
element, Transformtransform); - public void Unlock();
- }
可以看出我們可以通過兩種Silverlight寫圖像的形式來實例化這個WriteableBitmap。一個是通過傳入已經初始化了的BitmapSource,另外一個是通過輸入圖像高度和寬度以及像素類型(有Bgr32和Pbgra32兩種,后面一種可以創(chuàng)建半透明圖像)。第5行的索引this[int index]可以用來讀或取像素點。
寫一個WriteableBitmap的流程是這樣的。實例化WriteableBitmap,調用Lock方法,寫像素點,調用Invalidate方法,最后是調用Unlock方式來釋放所有的Buffer并準備顯示。
如下文所示以描點的方式構建了整個Bgr32圖像
- private WriteableBitmap BuildTheImage
(int width, int height)- {
- WriteableBitmap wBitmap=new Writeable
Bitmap(width,height,PixelFormats.Bgr32);- wBitmap.Lock();
- for (int x = 0; x < width; x++)
- {
- for (int y = 0; y < height; y++)
- {
- byte[] brg = new byte[4];
- brg[0]=(byte)(Math.Pow(x,2) % 255);
//Blue, B- brg[1] = (byte)(Math.Pow(y,2)
% 255); //Green, G- brg[2] = (byte)((Math.Pow(x, 2) + Mat
h.Pow(y, 2)) % //Red, R- brg[3] = 0;
- int pixel = BitConverter.
ToInt32(brg, 0);- wBitmap[y * height + x] = pixel;
- }
- }
- wBitmap.Invalidate();
- wBitmap.Unlock();
- return wBitmap;
- }
Silverlight寫圖像的實現方法就為大家介紹到這里。