WPF允許使用Image元素顯示點陣圖。然而,按這種方法顯示圖片的方法完全是單向的。應用程式使用現成的點陣圖,讀取問題,併在視窗中顯示點陣圖。就其本身而言,Image元素沒有提供創建和編輯點陣圖信息的方法。 這正是WriteableBitmap類的用武之地。該類繼承自BitmapSource,BitmapS ...
WPF允許使用Image元素顯示點陣圖。然而,按這種方法顯示圖片的方法完全是單向的。應用程式使用現成的點陣圖,讀取問題,併在視窗中顯示點陣圖。就其本身而言,Image元素沒有提供創建和編輯點陣圖信息的方法。
這正是WriteableBitmap類的用武之地。該類繼承自BitmapSource,BitmapSource類是當設置Image.Source屬性時使用的類(不管是在代碼中直接設置圖像,還是在XAML中隱式地設置圖像)。但BitmapSource是只讀的點陣圖數據映射,而WriteableBitmap類是可修改的像素數組,為實現許多有趣得效果提供了可能。
一、生成點陣圖
為使用WriteableBitmap類生成一幅點陣圖,必須提供提供幾部分重要信息:以像素為單位的寬度和高度、兩個方向上的DPI解析度以及圖像格式。
下麵是創建一幅與當前圖像元素尺寸相同的點陣圖的示例:
// Create the bitmap, with the dimensions of the image placeholder. WriteableBitmap wb = new WriteableBitmap((int)img.Width, (int)img.Height, 96, 96, PixelFormats.Bgra32, null);
PixelFormats枚舉提供了許多像素格式,但只有一半格式唄認為是可寫入的並且得到了WriteableBitmap類的支持。下麵是可供使用的像素格式:
- Bgra32。這種格式使用32位sRGB顏色。這意味每個像素由32位(或4個位元組)表示。第1個位元組表示藍色通道的貢獻(作為從0到255之間的數字)。第2個位元組用於綠色通道,第3個位元組用於紅色通道,第4個位元組用於alpha值(0表示完全透明,255表示完全不透明)。正如可能看到的,顏色的順序(藍綠、紅和alpha)與名稱Bgra32中字母的順序是匹配的。
- Bgr32。.這種格式為每個像素使用4個位元組,就像Bgra32格式一樣。區別是忽略了alpha通道。當不需要透明度時可使用這種格式。
- Pbgra32。就像Bgra32格式一樣,該格式為每個像素使用4個位元組。區別在於處理半透明像素的方式。為了提高透明度計算的性能,每個顏色位元組是預先相乘的(因此在Pbgra32中有字母P)。這意味著每個顏色位元組被乘上了alpha值並除以255.在Bgra32格式中具有B、G、R、A值(255,100,0,200)的半透明像素,在Pbgra32格式中變成了(200,78,0,200)。
- BlackWhite、Gray2、Gray4、Gray8。這些格式是黑白和灰度格式。單詞Gray後面的數字和每像素的位置相對應。因此,這些格式是壓縮的,但它們不支持顏色。
- Indexed1、Indexed2、Indexed4、Indexed8。這些是索引格式,這意味著每個像素指向顏色調色板中的一個值。當使用這些格式中的某種格式時,必須做出WriteableBitmap構造函數的最後一個參數傳遞相應的ColorPalette對象。單詞Indexed後面的數字和每像素的位數相對應。索引格式是壓縮的,使用這些格式稍微複雜一些,並且分別支持更少的顏色——2、4、16以及256種顏色。
前三種格式——Bgra32、Bgr32以及Pbgra32——是最常見的選擇。
二、寫入WriteableBitmap對象
開始時,WriteableBitmap對象中所有位元組的值都是0。本質上,就是一個大的黑色的矩形。為使用內容填充WriteableBitmap對象,需要使用WritePixels()方法。WritePixels()方法將位元組數組複製到指定位置的點陣圖中,可調用WritePixels()方法設置單個像素、整幅點陣圖或選擇的某塊矩形區域。為從WriteableBitmap對象中獲取像素,需要使用CopyPixels()方法,該方法將希望獲取的多個位元組轉換成位元組數組。總之,WritePixels()和CopyPixels()方法沒有提供可供使用的最方便編程模型,但這是低級像素訪問需要付出的代價。
為成功地使用WritePixels()方法,需要理解圖像格式並需要理解如何將像素編碼到位元組。例如,在Bgra32類型的32位點陣圖中,每個像素需要4個位元組,每個位元組分別用於藍、綠、紅以及alpha成分。下麵的代碼顯示瞭如何手動設置這些數值,然後將它們轉換成數組:
int alpha = 0; int red = 0; int green = 0; int blue = 0; byte[] colorData={blue,gree,red,alpha};
需要註意,在此順序是很關鍵的。位元組數組必須遵循在Bgra32標準中設置的藍、綠、紅、alpha順序。
當調用WritePixels()方法時,提供Int32Rect對象以指定點陣圖中希望更新的矩形區域。Int32Rect封裝了4部分信息:更新區域左上角的X和Y坐標,以及更新區域的寬度和高度。
下麵的代碼採用在前面代碼中顯示的colorData數組,並使用該數組設置WriteableBitmap對象中的第一個像素:
// Define the update square (which is as big as the entire image). Int32Rect rect = new Int32Rect(0, 0, (int)img.Width, (int)img.Height); wb.WritePixels(rect, colorData, 0, 0);
使用這種方法,可創建生產WriteableBitmap對象的代碼常式。只需要迴圈處理圖像中的所有列和所有行,併在每次迭代中更新單個像素。
Random rand = new Random(); for (int x = 0; x < wb.PixelWidth; x++) { for (int y = 0; y < wb.PixelHeight; y++) { int alpha = 0; int red = 0; int green = 0; int blue = 0; // Determine the pixel's color. if ((x % 5 == 0) || (y % 7 == 0)) { red = (int)((double)y / wb.PixelHeight * 255); green = rand.Next(100, 255); blue = (int)((double)x / wb.PixelWidth * 255); alpha = 255; } else { red = (int)((double)x / wb.PixelWidth * 255); green = rand.Next(100, 255); blue = (int)((double)y / wb.PixelHeight * 255); alpha = 50; } // Set the pixel value. byte[] colorData = { (byte)blue, (byte)green, (byte)red, (byte)alpha }; // B G R Int32Rect rect = new Int32Rect(x, y, 1, 1); int stride = (wb.PixelWidth * wb.Format.BitsPerPixel) / 8; wb.WritePixels(rect, colorData, stride, 0); //wb.WritePixels(.[y * wb.PixelWidth + x] = pixelColorValue; } }
上述代碼包含一個額外細節:針對跨距(stride)的計算,WritePixels()方法需要跨距。從技術角度看,跨距是每行像素數據需要的位元組數量。可通過將每行中像素的數量乘上所使用格式的每像素位數(通常為4,如本例使用的Bgra32格式),然後將所得結果除以8,進而將其從位數轉換成位元組數。
完成每個像素的生產過程後,需要顯示最終點陣圖。通常將使用Image元素完成該工作:
img.Source = wb;
即使是在寫入和顯示點陣圖後,也仍可自由地讀取和修改WriteableBitmap對象中的像素,從而可以構建更特殊的用於點陣圖編輯以及點陣圖命中測試的常式。
三、更高效的像素寫入
儘管上一節中顯示的代碼可以工作,但並非最佳方法。如果需要一次性寫入大量像素數據——甚至是整幅圖像——最好使用更大的塊,因為調用WritePixels()方法需要一定的開銷,並且調用該方法越頻繁,應用程式的運行速度就越慢。
下圖顯示了一個測試應用程式。該測試程式通過使用沿著規則網格線散步的基本隨機模式填充像素來創建一幅動態點陣圖。本章示例採用兩種方法執行該任務:使用上一節中國解釋的逐像素方法和稍後介紹看到的一次寫入策略。如果測試該應用程式,將發現一次寫入技術快很多。
為一次更新多個像素,需要理解像素被打包進位元組數組的方式。無論使用哪種格式,更新緩衝區都將包括一維位元組數組。這個數組提供了用於圖像矩形區域中像素的數值,從左向右延伸填充每行,然後自上而下延伸。
為找到某個特定像素,需要使用以下公式,下移數行,然後一道該行中恰當的位置:
(x + y * wb.PixelWidth) * BitsPerPixel
例如,為設置一幅Bgra32格式(每個像素具有4個位元組)的點陣圖中額像素(40,100),需要使用下麵的代碼:
int pixelOffset = (x + y * wb.PixelWidth) * wb.Format.BitsPerPixel / 8; pixels[pixelOffset] = (byte)blue; pixels[pixelOffset + 1] = (byte)green; pixels[pixelOffset + 2] = (byte)red; pixels[pixelOffset + 3] = (byte)alpha;
根據上面的方法,下麵是創建前面示例的完整代碼,首先在一個數組中填充所有數據,然後值通過一次WritePixels()方法調用將其複製到WriteableBitmap對象中:
// Create the bitmap, with the dimensions of the image placeholder. WriteableBitmap wb = new WriteableBitmap((int)img.Width, (int)img.Height, 96, 96, PixelFormats.Bgra32, null); // Define the update square (which is as big as the entire image). Int32Rect rect = new Int32Rect(0, 0, (int)img.Width, (int)img.Height); byte[] pixels = new byte[(int)img.Width * (int)img.Height * wb.Format.BitsPerPixel / 8]; Random rand = new Random(); for (int y = 0; y < wb.PixelHeight; y++) { for (int x = 0; x < wb.PixelWidth; x++) { int alpha = 0; int red = 0; int green = 0; int blue = 0; // Determine the pixel's color. if ((x % 5 == 0) || (y % 7 == 0)) { red = (int)((double)y / wb.PixelHeight * 255); green = rand.Next(100, 255); blue = (int)((double)x / wb.PixelWidth * 255); alpha = 255; } else { red = (int)((double)x / wb.PixelWidth * 255); green = rand.Next(100, 255); blue = (int)((double)y / wb.PixelHeight * 255); alpha = 50; } int pixelOffset = (x + y * wb.PixelWidth) * wb.Format.BitsPerPixel / 8; pixels[pixelOffset] = (byte)blue; pixels[pixelOffset + 1] = (byte)green; pixels[pixelOffset + 2] = (byte)red; pixels[pixelOffset + 3] = (byte)alpha; } int stride = (wb.PixelWidth * wb.Format.BitsPerPixel) / 8; wb.WritePixels(rect, pixels, stride, 0); } // Show the bitmap in an Image element. img.Source = wb;
在實際應用程式中,可選擇折中方法。如果需要更新點陣圖中一塊較大的區域,不會一次寫入一個像素,因為這種方法的運行速度太慢。但也不會在記憶體中同時保存全部圖像數據,因為圖像數據可能會很大(畢竟,一幅每像素需要4個位元組的1000X1000像素的圖像需要將近4MB的記憶體,這一要求不會很過分,但是耶比較高)。相反,應當寫入一大塊圖像數據而不是單個像素,當一次生成一整幅點陣圖時尤其如此。
本章示例完整標記:

<Window x:Class="Drawing.GenerateBitmap" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="GenerateBitmap" Height="460" Width="472" SizeToContent="WidthAndHeight"> <Grid x:Name="LayoutRoot" Background="White"> <Grid.RowDefinitions> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <Button Content="Button" Grid.Row="1" Height="81" HorizontalAlignment="Left" Margin="106,90,0,0" Name="button1" VerticalAlignment="Top" Width="193" /> <Button Content="Generate Bitmap" Width="120" Margin="5" Padding="10" Click="cmdGenerate2_Click" HorizontalAlignment="Center"></Button> <Image Grid.Row="1" x:Name="img" Margin="5" Width="400" Height="300" IsHitTestVisible="False"></Image> </Grid> </Window>GenerateBitmap

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Drawing { /// <summary> /// GenerateBitmap.xaml 的交互邏輯 /// </summary> public partial class GenerateBitmap : Window { public GenerateBitmap() { InitializeComponent(); } private void cmdGenerate_Click(object sender, RoutedEventArgs e) { // Create the bitmap, with the dimensions of the image placeholder. WriteableBitmap wb = new WriteableBitmap((int)img.Width, (int)img.Height, 96, 96, PixelFormats.Bgra32, null); // Define the update square (which is as big as the entire image). Int32Rect rect = new Int32Rect(0, 0, (int)img.Width, (int)img.Height); byte[] pixels = new byte[(int)img.Width * (int)img.Height * wb.Format.BitsPerPixel / 8]; Random rand = new Random(); for (int y = 0; y < wb.PixelHeight; y++) { for (int x = 0; x < wb.PixelWidth; x++) { int alpha = 0; int red = 0; int green = 0; int blue = 0; // Determine the pixel's color. if ((x % 5 == 0) || (y % 7 == 0)) { red = (int)((double)y / wb.PixelHeight * 255); green = rand.Next(100, 255); blue = (int)((double)x / wb.PixelWidth * 255); alpha = 255; } else { red = (int)((double)x / wb.PixelWidth * 255); green = rand.Next(100, 255); blue = (int)((double)y / wb.PixelHeight * 255); alpha = 50; } int pixelOffset = (x + y * wb.PixelWidth) * wb.Format.BitsPerPixel / 8; pixels[pixelOffset] = (byte)blue; pixels[pixelOffset + 1] = (byte)green; pixels[pixelOffset + 2] = (byte)red; pixels[pixelOffset + 3] = (byte)alpha; } int stride = (wb.PixelWidth * wb.Format.BitsPerPixel) / 8; wb.WritePixels(rect, pixels, stride, 0); } // Show the bitmap in an Image element. img.Source = wb; } private void cmdGenerate2_Click(object sender, RoutedEventArgs e) { // Create the bitmap, with the dimensions of the image placeholder. WriteableBitmap wb = new WriteableBitmap((int)img.Width, (int)img.Height, 96, 96, PixelFormats.Bgra32, null); Random rand = new Random(); for (int x = 0; x < wb.PixelWidth; x++) { for (int y = 0; y < wb.PixelHeight; y++) { int alpha = 0; int red = 0; int green = 0; int blue = 0; // Determine the pixel's color. if ((x % 5 == 0) || (y % 7 == 0)) { red = (int)((double)y / wb.PixelHeight * 255); green = rand.Next(100, 255); blue = (int)((double)x / wb.PixelWidth * 255); alpha = 255; } else { red = (int)((double)x / wb.PixelWidth * 255); green = rand.Next(100, 255); blue = (int)((double)y / wb.PixelHeight * 255); alpha = 50; } // Set the pixel value. byte[] colorData = { (byte)blue, (byte)green, (byte)red, (byte)alpha }; // B G R Int32Rect rect = new Int32Rect(x, y, 1, 1); int stride = (wb.PixelWidth * wb.Format.BitsPerPixel) / 8; wb.WritePixels(rect, colorData, stride, 0); //wb.WritePixels(.[y * wb.PixelWidth + x] = pixelColorValue; } } // Show the bitmap in an Image element. img.Source = wb; } } }GenerateBitmap.xaml.cs