適用於圓形、橢圓等規則幾何圖形。在 Form_Paint 事件中重繪窗體區域:
var shape = new GraphicsPath();
shape.AddEllipse(0, 0, this.Height, this.Width);
this.Region = new Region(shape);
優點:程式碼極簡、無圖片依賴、效能最佳。缺點:無法實現複雜非幾何造型。
BackgroundImage = 圖片,TransparencyKey = 背景色,FormBorderStyle = None。坑點:用戶螢幕色深若超過 24 位,非透明區域會顯示異常。需提醒用戶調整顯示設定,體驗較差。
原理:讀取位圖每像素,將非透明色區域合併為矩形加入 GraphicsPath,最後指派給 Form.Region。關鍵演算法:
private static GraphicsPath CalculateControlGraphicsPath(Bitmap bitmap) {
var path = new GraphicsPath();
Color transparent = bitmap.GetPixel(0, 0); // 左上角為透明色
for (int y = 0; y < bitmap.Height; y++) {
int xStart = -1;
for (int x = 0; x < bitmap.Width; x++) {
if (bitmap.GetPixel(x, y) != transparent) {
if (xStart == -1) xStart = x;
} else if (xStart != -1) {
path.AddRectangle(new Rectangle(xStart, y, x - xStart, 1));
xStart = -1;
}
}
if (xStart != -1) // 行尾收尾
path.AddRectangle(new Rectangle(xStart, y, bitmap.Width - xStart, 1));
}
return path;
}
優點:支援任意複雜造型、執行期動態載入、無色深限制。缺點:大圖掃描耗時,啟動稍慢;需處理高 DPI 縮放。
透過 CreatePolygonRgn + SetWindowRgn 直接操作視窗區域:
[DllImport("gdi32.dll")]
private static extern IntPtr CreatePolygonRgn(ref POINT[] pts, int count, int mode);
[DllImport("user32.dll")]
private static extern int SetWindowRgn(IntPtr hWnd, IntPtr hRgn, ref bool redraw);
// 定義五個頂點構成不規則多邊形
var pts = new POINT[5] { ... };
var hRgn = CreatePolygonRgn(ref pts[0], 5, 1);
SetWindowRgn(this.Handle, hRgn, ref flag);
優點:極低記憶體佔用、適合簡單多邊形。缺點:僅限直線邊緣、需手動計算座標、非托管程式碼風險較高。
| 場景 | 推薦方案 | 關鍵注意 |
|---|---|---|
| 圓/橢圓/矩形圓角 | 方案一 | 最簡潔高效 |
| 設計師提供複雜造型圖片 | 方案三 | 預先快取 GraphicsPath;高 DPI 下用 1.5x/2x 圖 |
| 簡單多邊形、極致效能 | 方案四 | 座標用相對比例,配合 Resize 事件重算 |
| 快速原型、不追求完美 | 方案二 | 僅限內部工具,避開色深坑 |
WndProc 處理 WM_NCHITTEST 回傳 HTCAPTION 實現整體拖曳。WS_EX_TRANSPARENT + WS_EX_LAYERED 擴展樣式。附件提供完整範例專案(.NET 2.0 可升級),含動態掃描、GDI 多邊形、自訂軌跡動畫三種 Demo,建議下載實測體驗差異。