C# .NET 标签中的多种颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/275836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 21:09:04  来源:igfitidea点击:

Multiple colors in a C# .NET label

c#.netuser-interfacecolorslabel

提问by Cory

I'm looking for a way to display multiple colors in a single C#/.NET label. E.g the label is displaying a series of csv separated values that each take on a color depending on a bucket they fall into. I would prefer not to use multiple labels, as the values are variable length and I don't want to play with dynamic layouts. Is there a native support for this?

我正在寻找一种在单个 C#/.NET 标签中显示多种颜色的方法。例如,标签显示一系列 csv 分隔值,每个值根据它们落入的桶呈现颜色。我不想使用多个标签,因为这些值是可变长度的,我不想使用动态布局。是否有本地支持?

采纳答案by MusiGenesis

There is no native control in .NET that does this. Your best bet is to write your own UserControl (call it RainbowLabel or something). Normally you would have a custom label control inherit directly from Label, but since you can't get multi-colored text in one label, you would just inherit from UserControl.

.NET 中没有执行此操作的本机控件。最好的办法是编写自己的 UserControl(称为 RainbowLabel 或其他名称)。通常,您会拥有一个直接从 Label 继承的自定义标签控件,但由于您无法在一个标签中获得多色文本,因此您只能从 UserControl 继承。

For rendering the text, your UserControl could split the text on commas and then dynamically load a differently-colored Label for each chunk. A better way, however, would be to render the text directly onto your UserControl using the DrawString and MeasureString methods in the Graphics namespace.

为了呈现文本,您的 UserControl 可以用逗号分割文本,然后为每个块动态加载不同颜色的标签。但是,更好的方法是使用 Graphics 命名空间中的 DrawString 和 MeasureString 方法将文本直接呈现到您的 UserControl 上。

Writing UserControls in .NET is really not difficult, and this kind of unusual problem is exactly what custom UserControls are for.

.NET 中编写 UserControls 真的不难,而这种不寻常的问题正是自定义 UserControls 的目的。

Update: here's a simple method you can use for rendering the multi-colored text on a PictureBox:

更新:这里有一个简单的方法,可用于在 PictureBox 上呈现多色文本:

public void RenderRainbowText(string Text, PictureBox pb)
{
    // PictureBox needs an image to draw on
    pb.Image = new Bitmap(pb.Width, pb.Height);
    using (Graphics g = Graphics.FromImage(pb.Image))
    {
        // create all-white background for drawing
        SolidBrush brush = new SolidBrush(Color.White);
        g.FillRectangle(brush, 0, 0,
            pb.Image.Width, pb.Image.Height);
        // draw comma-delimited elements in multiple colors
        string[] chunks = Text.Split(',');
        brush = new SolidBrush(Color.Black);
        SolidBrush[] brushes = new SolidBrush[] { 
            new SolidBrush(Color.Red),
            new SolidBrush(Color.Green),
            new SolidBrush(Color.Blue),
            new SolidBrush(Color.Purple) };
        float x = 0;
        for (int i = 0; i < chunks.Length; i++)
        {
            // draw text in whatever color
            g.DrawString(chunks[i], pb.Font, brushes[i], x, 0);
            // measure text and advance x
            x += (g.MeasureString(chunks[i], pb.Font)).Width;
            // draw the comma back in, in black
            if (i < (chunks.Length - 1))
            {
                g.DrawString(",", pb.Font, brush, x, 0);
                x += (g.MeasureString(",", pb.Font)).Width;
            }
        }
    }
}

Obviously this will break if you have more than 4 comma-delimited elements in your text, but you get the idea. Also, there appears to be a small glitch in MeasureString that makes it return a width that is a couple pixels wider than necessary, so the multi-colored string appears stretched out - you might want to tweak that part.

显然,如果您的文本中有超过 4 个以逗号分隔的元素,这将中断,但您明白了。此外,MeasureString 中似乎存在一个小故障,使其返回的宽度比所需的宽度宽几个像素,因此多色字符串看起来被拉长了 - 您可能需要调整该部分。

It should be straightforward to modify this code for a UserControl.

为 UserControl 修改此代码应该很简单。

Note: TextRenderer is a better class to use for drawing and measuring strings, since it uses ints. Graphics.DrawString and .MeasureString use floats, so you'll get off-by-a-pixel errors here and there.

注意:TextRenderer 是用于绘制和测量字符串的更好类,因为它使用整数。Graphics.DrawString 和 .MeasureString 使用浮点数,所以你会在这里和那里得到逐个像素的错误。

Update: Forgetabout using TextRenderer. It is dog slow.

更新忘记使用 TextRenderer。它是狗慢。

回答by ljs

There is no native support for this; you will either have to use multiple labels or find a 3rd-party control that will provide this functionality.

对此没有本地支持;您将不得不使用多个标签或找到提供此功能的第 3 方控件。

回答by mrtaikandi

I don't think so. You should create one yourself.

我不这么认为。你应该自己创建一个。

回答by Phil Wright

You could try using a RichTextBox so that you can get multiple colors for the string and then make it read only and remove the border. Change the background color to the same as the Form it is on and you might get away with it.

您可以尝试使用 RichTextBox 以便您可以获得字符串的多种颜色,然后将其设为只读并删除边框。将背景颜色更改为与其所在表单相同的颜色,您可能会侥幸成功。

回答by Marc Gravell

As an alternative, you might do this as rtf or html in a suitable control (such as WebBrowser). It would probably take a bit more resources that you'd ideally like, but it'll work fairly quickly.

作为替代方案,您可以在合适的控件(例如 WebBrowser)中将其作为 rtf 或 html 执行。它可能会占用您理想中喜欢的更多资源,但它会运行得相当快。

回答by Timothy Khouri

If you are building your Windows app for people with XP and up, you can use WPF. Even if it's a Windows Forms app, you can add a WPF UserControl.

如果您正在为 XP 及更高版本的用户构建 Windows 应用程序,则可以使用 WPF。即使它是 Windows 窗体应用程序,您也可以添加 WPF UserControl。

I would then use a Label, and set the "Foreground" property to be a gradient of colors.

然后我会使用一个标签,并将“前景”属性设置为颜色渐变。

Or, in Windows Forms (no WPF), you could just use a "Flow Panel", and then in a for loop add multiple Labels as segments of your sentense... they will all "flow" together as if it was one label.

或者,在 Windows 窗体(无 WPF)中,您可以只使用“流面板”,然后在 for 循环中添加多个标签作为句子的片段……它们将全部“流动”在一起,就好像它是一个标签一样.

回答by MusiGenesis

As per your Question your requirement is simple like lable.Text = "This color is Red", So it have to display text like this "The color is" will be in Blue and "Red" will be red color .. This can be done like this

根据你的问题,你的要求很简单 lable.Text = "This color is Red",所以它必须显示这样的文本“颜色是”将是蓝色,“红色”将是红色..这可以这样做

lable.Text = "<span style='Color:Blue'>" + " The color is " +"</span>" + "<span style='Color:Red'>"Red"</span>"

回答by Yordan Georgiev

Slightly off topic ... You could check also:

稍微偏离主题......你也可以检查:

回答by Chris Wegener

You can simply use multiple labels. Set the font properties you want and then use the left. top and width properties to display the words you want displayed differently. This is assuming you are using windows forms.

您可以简单地使用多个标签。设置您想要的字体属性,然后使用左侧。top 和 width 属性来显示您想要以不同方式显示的单词。这是假设您使用的是 Windows 窗体。

回答by harry4516

I'm using colored labels quite often to mark keywords in red color etc. Like in Phil Wright's answer I use a RichTextBox control, remove the border and set the background color to SystemColors.Control.

我经常使用彩色标签以红色等标记关键字。就像在 Phil Wright 的回答中一样,我使用 RichTextBox 控件,删除边框并将背景颜色设置为 SystemColors.Control。

To write colored text the control is first cleared and then I use this function to append colored text:

要编写彩色文本,首先清除控件,然后使用此函数附加彩色文本:

private void rtb_AppendText(Font selfont, Color color, Color bcolor, 
                        string text, RichTextBox box)
    {
            // append the text to the RichTextBox control
            int start = box.TextLength;
            box.AppendText(text);
            int end = box.TextLength;

            // select the new text
            box.Select(start, end - start);
            // set the attributes of the new text
            box.SelectionColor = color;
            box.SelectionFont = selfont;
            box.SelectionBackColor = bcolor;
            // unselect
            box.Select(end, 0);

            // only required for multi line text to scroll to the end
            box.ScrollToCaret();
    }

If you want to run this function with "mono" then add a space before every new colored text, or mono will not set new the color correctly. This is not required with .NET

如果您想使用“mono”运行此功能,请在每个新的彩色文本之前添加一个空格,否则 mono 将无法正确设置新的颜色。这不是 .NET 所必需的

Usage:

用法:

myRtb.Text = "";
rtb_AppendText(new Font("Courier New", (float)10), 
                   Color.Red, SystemColors.Control, " my red text", myRtb);
rtb_AppendText(new Font("Courier New", (float)10), 
                   Color.Blue, SystemColors.Control, " followed by blue", myRtb);