C#单选框的自定义绘制方法

avatar
作者
筋斗云
阅读量:0

要自定义绘制C#单选框,可以通过继承自RadioButton控件并重写其OnPaint方法来实现。以下是一个简单的示例:

using System.Drawing; using System.Windows.Forms;  public class CustomRadioButton : RadioButton {     protected override void OnPaint(PaintEventArgs e)     {         base.OnPaint(e);          // 自定义绘制单选框         Rectangle boxRect = new Rectangle(0, (this.Height - 16) / 2, 16, 16);         e.Graphics.FillEllipse(Brushes.White, boxRect);         e.Graphics.DrawEllipse(Pens.Black, boxRect);          if (this.Checked)         {             Rectangle innerRect = new Rectangle(boxRect.X + 4, boxRect.Y + 4, 8, 8);             e.Graphics.FillEllipse(Brushes.Black, innerRect);         }          // 绘制文本         using (StringFormat sf = new StringFormat())         {             sf.LineAlignment = StringAlignment.Center;              Rectangle textRect = new Rectangle(boxRect.Right + 5, 0, this.Width - boxRect.Right - 5, this.Height);             e.Graphics.DrawString(this.Text, this.Font, Brushes.Black, textRect, sf);         }     } } 

在上面的示例中,我们继承自RadioButton控件,并重写了其OnPaint方法来自定义绘制单选框。我们首先绘制一个白色的圆形框,并用黑色描边,然后根据单选框是否被选中来填充一个黑色的圆形。最后,我们使用DrawString方法绘制单选框的文本。

要使用这个自定义的单选框控件,只需在窗体中添加一个CustomRadioButton控件即可。例如:

CustomRadioButton customRadioButton1 = new CustomRadioButton(); customRadioButton1.Text = "Option 1"; customRadioButton1.Location = new Point(10, 10); this.Controls.Add(customRadioButton1); 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!