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,手動雙緩衝較耗記憶體 (雙倍畫布)。
僅重繪無效區域 (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);
}