关于c#:我正在尝试在标签中以不同的颜色显示字符串,该如何执行..?

I am trying to show a string in label with diffrent color how to perform this..?

1
2
3
IDE = Visual Studio 2010  
Language = c# .net  
Technology = windows forms application

嗨,
我有3个标签

Label1详细信息:

1
2
label1.text ="Team1";  
label1.forecolor = Color.yellow;

Label2详细信息:

1
2
label2.text ="Team1";  
label2.forecolor = Color.green;

Label3详细信息:

1
2
label3.text ="Team1";  
label3.forecolor = Color.grey;

现在,我正在尝试的是:

1
label4.text ="Match between" + label1.text+" and" +label2.text+" at" +label3.text         ;

但是我的输出是将所有标签都设置为label4的相同颜色。
我希望它以不同的颜色显示。

我已经尝试过此解决方案以将不同的标签放入表单中,但它却重叠了。

那么有什么方法可以串联标签..?

有什么建议吗?


如果您愿意,可以创建一个UserControl并覆盖其OnPaint函数,以使用GDI用不同的颜色绘制这三段文本。它只需要一个简单的DrawString调用。

1
e.Graphics.DrawString("LabelText", this.Font, Brushes.Red, new Point(100, 100));

然后,您可以公开3个公共属性来控制3个文本块,还可以公开3个颜色属性来控制块的颜色。请注意,您需要根据OnPaint中的这些颜色创建SolidBrush,因为这正是DrawString的期望,例如:

1
2
using(SolidColorBrush br = new SolidColorBrush(mColor1)
    e.Graphics.DrawString("LabelText", this.Font, br, new Point(100, 100));

完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public partial class MultiColorLabel : Label
{
    public MultiColorLabel()
    {
        InitializeComponent();
    }

    public string Text1 { get; set; }
    public string Text2 { get; set; }
    public string Text3 { get; set; }

    public Color Color1 { get; set; }
    public Color Color2 { get; set; }
    public Color Color3 { get; set; }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        var g = e.Graphics;

        e.Graphics.DrawString("Match between", this.Font, Brushes.Black, 0, 0);
        var sz = g.MeasureString("Match between", this.Font).Width;

        using (SolidBrush sb = new SolidBrush(Color1))
            e.Graphics.DrawString(Text1, this.Font, sb, sz, 0);

        sz += g.MeasureString(Text1, this.Font).Width;

        e.Graphics.DrawString(" and", this.Font, Brushes.Black, sz, 0);
        sz += g.MeasureString(" and", this.Font).Width;

        using (SolidBrush sb = new SolidBrush(Color2))
            e.Graphics.DrawString(Text2, this.Font, sb, sz, 0);

        sz += g.MeasureString(Text2, this.Font).Width;

        e.Graphics.DrawString(" at", this.Font, Brushes.Black, sz, 0);
        sz += g.MeasureString(" at", this.Font).Width;

        using (SolidBrush sb = new SolidBrush(Color3))
            e.Graphics.DrawString(Text3, this.Font, sb, sz, 0);
    }
}

这是快照:

enter

因此您可以开发自己的User Control以在多个控件中显示文本。

您可以使用RichTextBox控件。


Label.Text仅返回字符串,不返回任何格式。因此,此处的所有文本将具有相同的label4颜色。您需要将标签添加到面板控件中。


Text`不会返回整个标签,而只会返回该标签的文本(字符串)。如果您想做自己想做的事,请阅读一些有关Graphics的帖子。