我刚刚写了一个简单的示例如何重载及重绘:
- //继承自System.Windows.Forms.Label控件。添加这个类到你的工程中后在ToolBox中可以看到一个控件,名为MultiColorLabel;
public class MultiColorLabel : System.Windows.Forms.Label
{
//重载绘图方法
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
//取得这个绘图对象Graphics
Graphics g = e.Graphics;
//绘制底色
Brush b = new SolidBrush(BackColor);
g.FillRectangle(b, e.ClipRectangle);
//绘制第一段文本
Brush bRed = new SolidBrush(Color.Red); //头两个字符用红色绘制
g.DrawString(Text.Substring(0, 2), this.Font, bRed, e.ClipRectangle); //在失效区域内绘制
SizeF size1 = g.MeasureString(Text.Substring(0, 2), this.Font); //计算头两个字符绘制后的大小
Rectangle rect2 = e.ClipRectangle; //计算绘制完头两个字符后的失效区域
rect2.X = (int)(e.ClipRectangle.Left + size1.Width);
rect2.Width = (int)(e.ClipRectangle.Width - size1.Width);
Brush bGreen = new SolidBrush(Color.Green); //绘制后面的字符,用绿色
g.DrawString(Text.Substring(2), this.Font, bGreen, rect2);
}
}