using AntdUI; using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace JinYuan.ControlLib { public partial class CustomGroupBox : GroupBox { private Color darkBorderColor = Color.FromArgb(64, 64, 64); private Color lightBorderColor = Color.FromArgb(217, 217, 217); private Color darkForeColor = Color.White; private Color lightForeColor = Color.Black; private const int TextPadding = 4; public Color BorderColor { get; set; } = Color.Gray; private float _borderWidth = 1f; private float _cornerRadius = 5f; [Category("Appearance")] [DefaultValue(1f)] public float BorderWidth { get => _borderWidth; set { _borderWidth = value; Invalidate(); } } [Category("Appearance")] [DefaultValue(5f)] public float CornerRadius { get => _cornerRadius; set { _cornerRadius = value; Invalidate(); } } public CustomGroupBox() { SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); UpdateTheme(Config.IsDark); } public void UpdateTheme(bool isDark) { ForeColor = isDark ? darkForeColor : lightForeColor; Invalidate(); } protected override void OnPaint(PaintEventArgs e) { var g = e.Graphics; g.SmoothingMode = SmoothingMode.AntiAlias; var borderColor = Config.IsDark ? darkBorderColor : lightBorderColor; var textSize = g.MeasureString(Text, Font); var textWidth = (int)Math.Ceiling(textSize.Width) + TextPadding * 2; var textHeight = (int)Math.Ceiling(textSize.Height); var textRect = new Rectangle(TextPadding, 0, textWidth, textHeight); var borderRect = new Rectangle((int)(_borderWidth / 2), textHeight / 2, Width - 1 - (int)_borderWidth, Height - textHeight / 2 - 1 - (int)_borderWidth); //绘制边框颜色 using (var pen = new Pen(BorderColor, BorderWidth)) { e.Graphics.DrawRectangle(pen, 0, 0, Width - BorderWidth, Height - BorderWidth); } // 绘制背景 using (var brush = new SolidBrush(BackColor)) { g.FillRectangle(brush, ClientRectangle); } // 创建圆角矩形路径 using (var path = GetRoundedRectanglePath(borderRect, _cornerRadius)) { // 绘制边框 using (var pen = new Pen(borderColor, _borderWidth)) { g.DrawPath(pen, path); } } // 绘制标题文本背景 using (var brush = new SolidBrush(BackColor)) { g.FillRectangle(brush, textRect); } // 绘制标题文本 using (var brush = new SolidBrush(ForeColor)) { g.DrawString(Text, Font, brush, textRect, new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }); } } private GraphicsPath GetRoundedRectanglePath(Rectangle rect, float radius) { GraphicsPath path = new GraphicsPath(); float diameter = radius * 2; RectangleF arcRect = new RectangleF(rect.Location, new SizeF(diameter, diameter)); // 左上角 path.AddArc(arcRect, 180, 90); // 顶边 arcRect.X = rect.Right - diameter; path.AddArc(arcRect, 270, 90); // 右边 arcRect.Y = rect.Bottom - diameter; path.AddArc(arcRect, 0, 90); // 底边 arcRect.X = rect.Left; path.AddArc(arcRect, 90, 90); path.CloseFigure(); return path; } } }