1.首先激活Label的Paint事件
2.在Paint事件中进行计算
一个汉字所占用的高度和宽度
例:第一个字符为汉字
var size1 = TextRenderer.MeasureText(str.Substring(0, 1), lbl.Font)
var size2 = TextRenderer.MeasureText(str.Substring(0, 2), lbl.Font)
int width = size2.width - size1.width;
int height = size1.height;
同理求得 标点/字母/数字 的高度和宽度(高度与汉字的高度相同,宽度不同,需要额外进行计算,若只有汉字,没有标点,可以不进行该处计算)
注:str为Label的Text内容
lbl为Label的Name
3.在Paint事件中进行计算,获取指定不同颜色字符串位置
string strTemp = str.Substring(0, str.IndexOf(strContent))
int length = strTemp.length;
注:str为Label的Text内容
strContent为指定不同颜色字符串
strTemp为指定不同颜色字符串前面的字符串
length为strTemp字符串的宽度
区分strTemp字符串中汉字的数量以及 字母/数字/标点 的数量从而计算获得strContent字符串在Label中的x坐标位置
Point pointTemp = new Point(count * width + countSym * widthSym, height);
注:pointTemp为指定不同颜色字符串在Label中的坐标位置
count 为指定不同颜色字符串前方字符串中汉字的数量
width为汉字的宽度
countSym为同理求得前方字符串中 字母/数字/标点 的数量
widthSym为同理求得 字母/数字/标点 的宽度
4.为指定不同颜色字符串重新上色
TextRenderer.DrawText(e.Graphics, strContent, lbl.Font, pointTemp, Color.Red);
注:strContent 为指定不同颜色字符串
lbl为Label的Name
pointTemp为指定不同颜色字符串在Label中的坐标位置
Color.Red为指定的颜色
补充:若Label内容中有多处不同颜色的字符串要标注,可以重复上诉内容。或进行循环,或进行多处判断。