使用不同颜色的Label控件(WinForm)

本文提供了一个基于System.Windows.Forms.Label的派生类MultiColorLabel的示例代码,演示了如何通过重载绘图方法实现文本颜色分段显示的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我刚刚写了一个简单的示例如何重载及重绘:
//继承自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);

}
}
这是原始版:)再持续改进一下。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值