改变子字符串的颜色

本文关键字:颜色 字符串 改变 | 更新日期: 2023-09-27 18:15:36

这可能吗?例如,如果我有一个标签:

lblsentence.Text = "Blue is my favourite colour, and Red is my least favourite"

我可以将"Blue""Red"更改为不同的颜色,并保留其余的标签文本默认(黑色)吗?

改变子字符串的颜色

试试下面

Web

Type colorType = typeof(System.Drawing.Color);
// We take only static property to avoid properties like Name, IsSystemColor ...
System.Reflection.PropertyInfo[] propInfos = colorType.GetProperties(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Public);
string[] Colors = propInfos.Select(m => m.Name).ToArray();
string str = lblsentence.Text;
foreach(string color in Colors)
{
    if(str.Contains(color))
    {
        string replaceColor = "<span style='color:" + color + "'>" + color + "</span>";
        str = str.Replace(color, replaceColor);
    }
}
lblsentence.Text = str;

我们可以在Win-Forms的情况下使用WebBrowser控件,而不是Label控件。

string str = "Blue is my favourite colour, and Red is my least favourite";
Type colorType = typeof(System.Drawing.Color);
// We take only static property to avoid properties like Name, IsSystemColor ...
System.Reflection.PropertyInfo[] propInfos = colorType.GetProperties(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Public);
string[] Colors = propInfos.Select(m => m.Name).ToArray();
foreach (string color in Colors)
{
    if (str.Contains(color))
    {
        string replaceColor = "<span style='color:" + color + "'>" + color + "</span>";
        str = str.Replace(color, replaceColor);
    }
}            
webBrowser1.DocumentText = str;

下面是一个富文本框控件

的示例
        // set the selection at the end of the box and set selection to 0
        richTextBox1.SelectionStart = richTextBox1.SelectionLength;
        richTextBox1.SelectionLength = 0;

        richTextBox1.SelectionColor = Color.Blue;
        richTextBox1.AppendText("hello ");
        richTextBox1.SelectionColor = Color.Red;
        richTextBox1.AppendText("World");
        // set back the default color
        richTextBox1.SelectionColor = richTextBox1.ForeColor;

如前所述,Wiforms标签不支持多种前置颜色。你要么需要一个RichTextBox或自定义控件。

我建议你使用HtmlRenderer库,它提供了你可以使用的HtmlLabel控制。您所要做的就是将文本转换为有效的Html

为什么不在表单上绘制自己的文本呢?e.Graphics.DrawString()会帮助你的。

private void Form_Paint(object sender, PaintEventArgs e)
{
    Font font = this.Font;
    int iLocation = 10;
    e.Graphics.DrawString("Blue", font, Brushes.Blue, new PointF(iLocation, 100));
    iLocation += e.Graphics.MeasureString("Blue", font) + 5;    
    e.Graphics.DrawString(" is my favourite colour, and ", font, Brushes.Black, new PointF(iLocation, 100));
    iLocation += e.Graphics.MeasureString(" is my favourite colour, and ", font) + 5;
    e.Graphics.DrawString("Red", font, Brushes.Red, new PointF(iLocation, 100));
    iLocation += e.Graphics.MeasureString("Red", font) + 5;
    e.Graphics.DrawString(" is my least favourite", font, Brushes.Black, new PointF(iLocation, 100));    
}