using System.Drawing;
using System.Windows.Forms;
namespace ControlLib.控件
{
public partial class CustomGroupBox : GroupBox
{
public CustomGroupBox()
{
InitializeComponent();
// 设置样式
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.DoubleBuffer, true);
this.SetStyle(ControlStyles.Selectable, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
}
private Color borderColor = Color.Black;
private Color textColor = Color.Black;
public Color BorderColor
{
get { return borderColor; }
set { borderColor = value; }
}
public Color TextColor
{
get { return textColor; }
set { textColor = value; }
}
protected override void OnPaint(PaintEventArgs e)
{
// 创建一个新的字体,用于绘制文本
Font textFont = new Font(this.Font.FontFamily, this.Font.Size, this.Font.Style);
SizeF textSize = e.Graphics.MeasureString(this.Text, textFont);
// 计算文本的水平位置,使其居中
float x = (this.Width - textSize.Width) / 2;
float y = 0;
// 绘制文本
e.Graphics.DrawString(this.Text, textFont, new SolidBrush(textColor), x, y); // 使用 textColor 绘制文本
// 重新绘制边框,避免与文本重叠
using (Pen borderPen = new Pen(borderColor))
{
// 绘制左边框
e.Graphics.DrawLine(borderPen, 0, this.Font.Height / 2, 0, this.Height - 1);
// 绘制上边框,留出文本左右边距
float leftMargin = 5; // 左边距,可以根据需要调整
float rightMargin = 5; // 右边距,可以根据需要调整
e.Graphics.DrawLine(borderPen, 0, this.Font.Height / 2, x - leftMargin, this.Font.Height / 2);
e.Graphics.DrawLine(borderPen, x + textSize.Width + rightMargin, this.Font.Height / 2, this.Width - 1, this.Font.Height / 2);
// 绘制右边框
e.Graphics.DrawLine(borderPen, this.Width - 1, this.Font.Height / 2, this.Width - 1, this.Height - 1);
// 绘制下边框
e.Graphics.DrawLine(borderPen, 0, this.Height - 1, this.Width - 1, this.Height - 1);
}
}
}
}
仔细分析此代码,在保证原有功能正常的基础上开放绘制圆角矩形的属性。