首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Windows Forms GDI+ 繪圖核心技術:Paint 事件、雙緩衝、智能重繪與效能優化

     編輯:關於.NET

繪圖基本概念

WinForms 採 GDI+。當視窗「髒了」(縮放、遮蓋、還原) 進入 Invalidated 狀態,系統發送 Paint 訊息,封裝為 Paint 事件。PaintEventArgs 提供:

  • Graphics:繪圖畫布
  • ClipRectangle:需重繪區域 (無效區)

設定 ControlStyles.ResizeRedraw 使縮放時整個客戶區失效重繪。

簡單繪圖範例

private void BasicX_Paint(object sender, PaintEventArgs e) {
    Graphics g = e.Graphics;
    using (Pen p = new Pen(Color.Red)) {
        int w = ClientRectangle.Width, h = ClientRectangle.Height;
        g.DrawLine(p, 0, 0, w, h);
        g.DrawLine(p, 0, h, w, 0);
    }
}

雙緩衝繪圖技術

原理:先繪製到記憶體 Bitmap,完成後一次 DrawImage 送至螢幕,消除閃爍。

private void SpiderWeb_DblBuff_Paint(object sender, PaintEventArgs e) {
    using (Bitmap bmp = new Bitmap(ClientRectangle.Width, ClientRectangle.Height))
    using (Graphics g = Graphics.FromImage(bmp)) {
        g.Clear(BackColor); // 需配合 ControlStyles.Opaque
        g.SmoothingMode = SmoothingMode.AntiAlias; // 反鋸齒
        LineDrawRoutine(g, Pens.Blue);
        e.Graphics.DrawImage(bmp, 0, 0);
    }
}

關鍵設定:SetStyle(ControlStyles.ResizeRedraw | ControlStyles.Opaque, true),Opaque 表示自行清除背景,配合 g.Clear 進一步減少閃爍。

內建 DoubleBuffered 屬性 (PictureBox 等) 已優化使用 DIB,手動雙緩衝較耗記憶體 (雙倍畫布)。

智能重繪 (Smart Invalidation)

僅重繪無效區域 (e.ClipRectangle) 或自訂 Region,大幅提升效能。

  • 基本:在 Paint 直接用 e.ClipRectangle 繪製。
  • 進階:覆寫 OnPaintBackground/OnPaint,用 Graphics.SetClip(region, CombineMode.Exclude) 排除區域,FillRegion 繪製特定形狀 (如文字輪廓)。
protected override void OnPaintBackground(PaintEventArgs e) {
    base.OnPaintBackground(e);
    e.Graphics.SetClip(textRegion, CombineMode.Exclude);
    e.Graphics.FillRectangle(backgroundBrush, e.ClipRectangle);
}
protected override void OnPaint(PaintEventArgs e) {
    base.OnPaint(e);
    e.Graphics.FillRegion(foregroundBrush, textRegion);
}

結論

  1. 正確設定 ControlStyles、處理 Paint 事件是基礎。
  2. 權衡記憶體與效果後使用雙緩衝。
  3. 繪製前思考:僅重繪必要區域 (Region/ClipRectangle) 最省資源。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved