1、雙緩存:把複雜的繪圖過程寫到內存裏,然後把內存裏的內容一次性的貼到要顯示的元素上。耗資源少、畫面流暢。
2、使用WriteableBitmap。
3、繪製到Image上:
width = (int)OutCanvas.ActualWidth;
height = (int)OutCanvas.ActualHeight;
if (width > 0 && height > 0)
{
DisplayImage.Width = width;
DisplayImage.Height = height;
wBitmap = new WriteableBitmap(width, height, 72, 72, PixelFormats.Bgr24, null);
DisplayImage.Source = wBitmap;
}
4、要使用GDI+:先把WriteableBitmap的後臺緩存交給Bitmap管理,然後使用Bitmap的Graphics進行繪製。
wBitmap.Lock();
Bitmap backBitmap = new Bitmap(width, height, wBitmap.BackBufferStride, System.Drawing.Imaging.PixelFormat.Format24bppRgb, wBitmap.BackBuffer);
Graphics graphics = Graphics.FromImage(backBitmap);
graphics.Clear(System.Drawing.Color.White);//整張畫布置爲白色
//畫一些隨機線
Random rand = new Random();
for (int i = 0; i < 100; i++)
{
int x1 = rand.Next(width);
int x2 = rand.Next(width);
int y1 = rand.Next(height);
int y2 = rand.Next(height);
graphics.DrawLine(Pens.Red, x1, y1, x2, y2);
}
graphics.Flush();
graphics.Dispose();
graphics = null;
backBitmap.Dispose();
backBitmap = null;
wBitmap.AddDirtyRect(new Int32Rect(0, 0, width, height));
wBitmap.Unlock();