Windows 抽象視訊卡差異:應用程式呼叫 GDI+ API → GDI+ 內部轉發至特定顯示驅動程式。開發者無需關心數百種顯示卡指令集。同樣 API 亦支援印表機、記憶體位圖等裝置,實現「螢幕所見即列印所得」。
ClipBounds、Transform、CompositingMode 等進階狀態
public Form1() {
InitializeComponent();
BackColor = Color.White; // 設計師自動產生
using (var g = CreateGraphics()) {
Show(); // 確保視窗句柄有效
var bluePen = new Pen(Color.Blue, 3);
g.DrawRectangle(bluePen, 0, 0, 50, 50);
var redPen = new Pen(Color.Red, 2);
g.DrawEllipse(redPen, 0, 50, 80, 60);
}
}
// 座標原點:客戶區左上角 (0,0),X 右、Y 下
WM_PAINT → 觸發 OnPaint / Paint 事件要求重繪。
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
var g = e.Graphics; // 系統準備好、已套用剪裁區的 Graphics
// 繪圖邏輯...
g.DrawRectangle(Pens.Blue, 0, 0, 50, 50);
g.DrawEllipse(Pens.Red, 0, 50, 80, 60);
}
| 方法 | 行為 | 用途 |
|---|---|---|
Invalidate() | 標記客戶區需重繪,發佈 WM_PAINT (非同步) | 效能最佳,批次合併重繪 |
Update() | 立即處理待決 WM_PAINT (同步) | 需即時視覺回饋時 |
Refresh() | Invalidate() + Update() | 強制立即完整重繪 |
public Form1() {
InitializeComponent();
// 雙緩衝三件套
SetStyle(ControlStyles.OptimizedDoubleBuffer |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.UserPaint, true);
// 或簡單啟用
this.DoubleBuffered = true;
}
原理:離屏位圖繪圖完成一次性 BitBlt 到螢幕,避免使用者看到中間狀態。
| 類別 | 用途 |
|---|---|
Pen | 線條、框線 (顏色、寬度、樣式、端點) |
Brush / SolidBrush / LinearGradientBrush / TextureBrush | 填充內部 (純色、漸層、材質) |
Font / StringFormat | 文字繪製 (字型、對齊、截斷) |
GraphicsPath | 複雜幾何圖形組合 (曲線、封閉區域) |
Region | 不規則區域裁剪、點擊測試 |
Matrix | 仿射轉換 (平移/旋轉/縮放/傾斜) |
Image / Bitmap / Metafile | 位圖/向量圖載入、繪製、儲存 |
var pd = new PrintDocument();
pd.PrintPage += (s, e) => {
// e.Graphics 即為印表機裝置的 Graphics
e.Graphics.DrawString("Hello Printer", Font, Brushes.Black, 100, 100);
};
pd.Print(); // 彈出列印對話框並輸出
同一套繪圖邏輯,傳入螢幕 Graphics 顯示,傳入印表機 Graphics 列印 — 體現 GDI+ 裝置獨立核心價值。