C#怎么写一个圆形或者椭圆型的自定义控件
开发的新的控件,一般继承自Control,重写OnPaint方法;还要自己写添加事件、处理消息等等。这样的控件,对应你的业务可以达到很好的效果,功能最灵活。同时对开发人员要求也最高,一般要了解图形绘制GDI+以及API的一些知识。比如,我们需要一个类似Label的控件,但是不需要Label那么多的属性和方法。那么就自己开发一个类似Label的自定义控件。
如下代码:直接继承自Control,其它代码会自动生成好。
[csharp] view plaincopyprint?
[ToolboxItem(true)]
public partial class CustomClassifyLabelItem : Control
{
private Color mColorOut = Color.FromArgb(255, 137, 37);
private StringFormat format;
private Color textColor;
private Font strFormat = new Font("宋体", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(134)));
public StringFormat Format
{
get
{
if (format == null)
{
format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
format.FormatFlags = StringFormatFlags.NoWrap;
format.Trimming = StringTrimming.EllipsisCharacter;
}
return format;
}
}
public Color TextColor
{
get
{
{
textColor = Color.FromArgb(22, 95, 162);
}
return textColor;
}
}
public CustomClassifyLabelItem()
{
InitializeComponent();
this.MouseEnter += new EventHandler(UCSelectClassifyItem_MouseEnter);
this.MouseLeave += new EventHandler(UCSelectClassifyItem_MouseLeave);
}
void UCSelectClassifyItem_MouseLeave(object sender, EventArgs e)
{
strFormat = new Font("宋体", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(134)));
Invalidate();
}
void UCSelectClassifyItem_MouseEnter(object sender, EventArgs e)
{
strFormat = new Font("宋体", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(134)));
Invalidate();
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
Graphics graphics = pe.Graphics;
using (SolidBrush b = new SolidBrush(TextColor))
{
graphics.DrawString(this.Text, strFormat, b, new Rectangle(0, 0, this.Width, this.Height), Format);
}
graphics.Dispose();
}
}