要自定義繪制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);