Multiple Colors in a C# .Net Label

Multiple colors in a C# .NET label

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.

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.

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

Update: here's a simple method you can use for rendering the multi-colored text on a 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.

It should be straightforward to modify this code for a 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.

Update: Forget about using TextRenderer. It is dog slow.

Changing the color of a part of a label in c#

Assuming that you really want different colors and fonts within the same label, I would recommend using a RichTextBox instead of a Label, like also mentioned in Rotem's duplicate proposal. It's quite easy to use:

RichTextBox rtb1 = new RichTextBox();
rtb1.SelectionColor = Color.Red;
rtb1.AppendText("Hello ");
rtb1.SelectionColor = Color.Green;
rtb1.AppendText("World");

Likewise with RichTextBox.SelectionFont...

Edit: for the sake of completeness - here are the changes to make it look/react like a label:

rtb1.BackColor = System.Drawing.SystemColors.Control;
rtb1.BorderStyle = System.Windows.Forms.BorderStyle.None;
rtb1.Enabled = false;
rtb1.Multiline = false;
rtb1.ReadOnly = true;

partially colored label in C#

There is no native control in .NET(winform) that does this.try this Label With multiple colors

c# web forms how to take two or more colors in one label text

That's not possible. You could either use a richtextbox and remove borders and make it non editable so it looks like a label or use a HTML control and use HTML markup.

Here's a xaml example of using a richtextbox like a label

<RichTextBox BorderStyle="none" Enabled="true" ReadOnly="true" Height="160" HorizontalAlignment="Left" Margin="43,20,0,0" Name="richTextBox1" VerticalAlignment="Top" Width="258" TextChanged="richTextBox1_TextChanged">
<FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Paragraph>
<Run Foreground="Red">Red</Run>
<Run Foreground="Green">Green</Run>
</Paragraph>
</FlowDocument>
</RichTextBox>

Here's a code example

Paragraph para = new Paragraph();
Run run1 = new Run("welcome to stackoverflow ");
run1.Foreground = Brushes.Red;
Run run2 = new Run(textbox1.text);
run2.Foreground = Brushes.Green;
para.Inlines.Add(run1);
para.Inlines.Add(run2);
// Get the document
FlowDocument doc = richTextBox1.Document;
// Clear existing content
doc.Blocks.Clear();
// Add new content
doc.Blocks.Add(para);

How to change the color of a part of a label c#

The Label control doesn't natively support multiple colors, but the RichTextBox control does! And you can set it's properties to look like a label.

For example, to make it look like a label:

private void Form1_Load(object sender, EventArgs e)
{
// Make the RichTextBox look and behave like a Label control
richTextBox1.BorderStyle = BorderStyle.None;
richTextBox1.BackColor = System.Drawing.SystemColors.Control;
richTextBox1.ReadOnly = true;
richTextBox1.Text = "Hipopotamus";

// I added a small, blank Label control to the form which I use to capture the Focus
// from this control, so the user can't see the caret or select/highlight/edit text
richTextBox1.GotFocus += (s, ea) => { lblHidden.Focus(); };
}

Then a method to highlight a search term by setting selection start and length and changing selected colors:

private void HighlightSearchText(string searchText, RichTextBox control)
{
// Make all text black first
control.SelectionStart = 0;
control.SelectionLength = control.Text.Length;
control.SelectionColor = System.Drawing.SystemColors.ControlText;

// Return if search text isn't found
var selStart = control.Text.IndexOf(searchText);
if (selStart < 0 || searchText.Length == 0) return;

// Otherwise, highlight the search text
control.SelectionStart = selStart;
control.SelectionLength = searchText.Length;
control.SelectionColor = Color.Red;
}

For a test and to show usage, I added a txtSearch textbox control to the form and call the method above in the TextChanged event. Run the form, and type into the textbox to see the results:

private void txtSearch_TextChanged(object sender, EventArgs e)
{
HighlightSearchText(txtSearch.Text, richTextBox1);
}

Richtextbox multiple back colors

This is a label used as a ProgressBar.

Just an example (quite raw, what I could do with the time I had), but it shows how you can paint the surface of a Control that provides a Paint() event.

It uses a Timer class to increase a value and generates a progress bar effect by calling the Label.Invalidate() method, which raises the Label's Paint event, executing whatever code you have in the label1_Paint() handler.

If you want to test it, paste this code inside a Form which contains a Button (button1) to start the Timer and a Label (label1) that generates the graphic effect.

Then assign the two events - Click() to the Button and Paint() to the Label.

This is how it looks like:

Sample Image

Timer timer;
private bool TimerStarted = false;
private float ProgressMaxValue = 100;
private float Progress = 0;
private int seconds = 0;
private int cents = 0;

private void button1_Click(object sender, EventArgs e)
{
if (TimerStarted) { TimerStop(); return; }
timer = new Timer();
timer.Interval = 20;
Progress = 0;
seconds = 0;
cents = 0;
timer.Tick += (s, ev) => {
++Progress;
if (Progress > ProgressMaxValue) { TimerStop(); return; }
cents += (timer.Interval / 5);
if (cents > 99) { cents = 0; ++seconds; }
this.label1.Invalidate();
};
TimerStarted = true;
timer.Start();
}

private void TimerStop()
{
timer.Stop();
timer.Dispose();
TimerStarted = false;
}

private void label1_Paint(object sender, PaintEventArgs e)
{
StringFormat format = new StringFormat() {
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};

e.Graphics.Clear(this.label1.BackColor);
Rectangle rect = label1.ClientRectangle;
rect.Inflate(-1, -1);
e.Graphics.DrawRectangle(Pens.LimeGreen, rect);
RectangleF ProgressBar = new RectangleF(
new PointF(3, 3),
new SizeF((((float)rect.Width - 3) / ProgressMaxValue) * Progress, rect.Height - 4));
e.Graphics.FillRectangle(Brushes.YellowGreen, ProgressBar);
e.Graphics.DrawString($"0.{seconds.ToString("D2")}.{cents.ToString("D2")}", label1.Font, Brushes.White, rect, format);
}


Related Topics



Leave a reply



Submit