如圖所示,邊框呈現凹凸感:頂/左邊亮白色,底/右邊暗灰色,模擬 3D 凸起或凹陷效果。
// 設計器拖入 GroupBox,或代碼創建
GroupBox gb = new GroupBox();
gb.Text = "分組標題"; // 可選
gb.Location = new Point(20, 20);
gb.Size = new Size(300, 200);
// 系統自動繪製 3D 邊框(視系統主題而定)
this.Controls.Add(gb);
public class Panel3D : Panel {
public Color LightColor { get; set; } = Color.White; // 高亮色
public Color DarkColor { get; set; } = Color.Gray; // 陰影色
public int BorderWidth { get; set; } = 2; // 邊框寬度
public Panel3D() {
this.SetStyle(ControlStyles.AllPaintingInWmPaint |
ControlStyles.UserPaint |
ControlStyles.OptimizedDoubleBuffer, true);
}
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
Graphics g = e.Graphics;
Rectangle rect = this.ClientRectangle;
int w = BorderWidth;
// 繪製四條邊:頂/左亮,底/右暗
using (Pen lightPen = new Pen(LightColor, w), darkPen = new Pen(DarkColor, w)) {
// 頂邊
g.DrawLine(lightPen, rect.Left, rect.Top, rect.Right, rect.Top);
// 左邊
g.DrawLine(lightPen, rect.Left, rect.Top, rect.Left, rect.Bottom);
// 底邊
g.DrawLine(darkPen, rect.Left, rect.Bottom, rect.Right, rect.Bottom);
// 右邊
g.DrawLine(darkPen, rect.Right, rect.Top, rect.Right, rect.Bottom);
}
}
}
// 使用
Panel3D panel = new Panel3D();
panel.Location = new Point(20, 20);
panel.Size = new Size(300, 200);
panel.BorderWidth = 2;
panel.LightColor = Color.FromArgb(255, 255, 255);
panel.DarkColor = Color.FromArgb(128, 128, 128);
this.Controls.Add(panel);
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
Graphics g = e.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
Rectangle rect = new Rectangle(0, 0, Width - 1, Height - 1);
int radius = 8;
using (GraphicsPath path = GetRoundRectPath(rect, radius)) {
// 繪製頂左亮弧 + 底右暗弧(需拆分路徑或多次繪製)
// 簡化:整體用漸變筆刷模擬 3D
using (LinearGradientBrush brush = new LinearGradientBrush(
rect, Color.White, Color.Gray, LinearGradientMode.ForwardDiagonal)) {
using (Pen pen = new Pen(brush, BorderWidth)) {
g.DrawPath(pen, path);
}
}
}
}
private GraphicsPath GetRoundRectPath(Rectangle rect, int radius) {
GraphicsPath path = new GraphicsPath();
path.AddArc(rect.X, rect.Y, radius * 2, radius * 2, 180, 90);
path.AddArc(rect.Right - radius * 2, rect.Y, radius * 2, radius * 2, 270, 90);
path.AddArc(rect.Right - radius * 2, rect.Bottom - radius * 2, radius * 2, radius * 2, 0, 90);
path.AddArc(rect.X, rect.Bottom - radius * 2, radius * 2, radius * 2, 90, 90);
path.CloseFigure();
return path;
}
| 場景 | 推薦 |
|---|---|
| 快速搭建、標準表單分組 | GroupBox |
| 需自定義顏色、圓角、線寬、動畫 | 自定義 Panel3D |
| 高性能、大量邊框 | Override OnPaint + 緩存 GraphicsPath |
onBindViewHolder 全量觸發卡頓:佈局測量導致的錯誤回收機制
ASP.NET 後台管理系統設計:用戶表、日誌表、權限控制
Android ListView 中 Item 內按鈕的點擊監聽實現
Visual Studio 2013 入門指南:從 Code::Blocks 轉型的 C/C++ 開發者必看
Java 統計字符串中子串出現次數:正則與手動遍歷兩種實現
C++ this 指針為何是常量指針 (T* const)?底層機制、函數簽名關聯與不可修改性深度解析