Windows Forms / WPF 中,控件邊框由 GraphicsPath 定義幾何形狀,在 Paint 事件中用 Pen 繪製路徑。關鍵步驟:
GraphicsPath.AddLines(points) 構建閉合路徑。e.Graphics.DrawPath(pen, path) 繪製。this.Region = new Region(path) 實現**點擊命中測試**也為圓角。
public static GraphicsPath CreateRoundRectPath(Rectangle bounds, int radius) {
var path = new GraphicsPath();
int d = radius * 2;
// 確保半徑不超過寬高一半
d = Math.Min(d, Math.Min(bounds.Width, bounds.Height));
// 4 個圓弧 + 4 條直線,順序:左上 → 右上 → 右下 → 左下
path.AddArc(bounds.X, bounds.Y, d, d, 180, 90); // 左上
path.AddArc(bounds.Right - d, bounds.Y, d, d, 270, 90); // 右上
path.AddArc(bounds.Right - d, bounds.Bottom - d, d, d, 0, 90); // 右下
path.AddArc(bounds.X, bounds.Bottom - d, d, d, 90, 90); // 左下
path.CloseFigure();
return path;
}
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
public class RoundedPanel : Panel {
private int _radius = 10;
private Color _borderColor = Color.Blue;
private int _borderWidth = 2;
public int Radius { get => _radius; set { _radius = value; Invalidate(); } }
public Color BorderColor { get => _borderColor; set { _borderColor = value; Invalidate(); } }
public int BorderWidth { get => _borderWidth; set { _borderWidth = value; Invalidate(); } }
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; // 抗鋸齒
var rect = new Rectangle(0, 0, Width - 1, Height - 1); // -1 防止右下邊框被切
using (var path = CreateRoundRectPath(rect, _radius))
using (var pen = new Pen(_borderColor, _borderWidth)) {
e.Graphics.DrawPath(pen, path);
}
// 可選:設置控件區域為圓角,實現點擊穿透圓角外部
// this.Region = new Region(path); // 注意:會影響子控件佈局,謹慎啟用
}
// 靜態工具方法可提取到公共類
private static GraphicsPath CreateRoundRectPath(Rectangle bounds, int radius) { /* 見上 */ }
}
<Border CornerRadius="10" BorderBrush="Blue" BorderThickness="2" Background="White">
<ContentControl Content="{Binding}" />
</Border>
WPF 保留模式渲染天生支持圓角,**無需手寫繪製代碼**,直接用 Border.CornerRadius。
// 漸變邊框
using (var brush = new LinearGradientBrush(rect, Color.Red, Color.Yellow, 45f))
using (var pen = new Pen(brush, 3)) {
e.Graphics.DrawPath(pen, path);
}
// 發光效果(多層疊加)
for (int i = 0; i < 5; i++) {
using (var pen = new Pen(Color.FromArgb(30, Color.Cyan), 2 + i * 2)) {
e.Graphics.DrawPath(pen, path);
}
}
// 虛線邊框
pen.DashStyle = DashStyle.Dash;
pen.DashPattern = new float[] { 5, 3 }; // 5像素實線,3像素空白
OnResize 重建,OnPaint 直接復用。Dispose 在 Dispose(bool) 中統一釋放。| 問題 | 原因 | 解決 |
|---|---|---|
| 右下角邊框缺失 | Rectangle 右下座標為 Width/Height,GDI+ 不畫最右/最下像素 | 用 Width-1, Height-1 構建 bounds |
| 半徑過大導致異常 | 半徑 > 寬/高一半 | radius = Math.Min(radius, Math.Min(w, h) / 2) |
| 子控件被 Region 裁剪 | this.Region = new Region(path) 影響命中測試 | 僅繪製邊框不設置 Region,或用 WPF |
| 高 DPI 模糊 | 未啟用 Per-Monitor DPI 感知 | 清單啟用 dpiAware,或用 WPF |
WinForms 用 GraphicsPath.AddArc 構建圓角矩形路徑,配合 OnPaint 繪製,封裝為 RoundedPanel 即可全項目復用。WPF 原生 Border.CornerRadius 更簡潔。掌握 **12 點座標算法 / AddArc 參數 / 抗鋸齒 / 雙緩衝 / 緩存路徑**,即能實現高性能、視覺優雅的圓角控件。