Draw text in random colors in C#


This example shows how you can draw text in random colors. The example Measure character positions in a drawn string in C# shows how to determine where the characters in a string will be drawn. This example uses similar code but it draws each character individually in a randomly selected color.

The program uses the following code to pick random colors.

// Return a random color.
private Random rand = new Random();
private Color[] colors =
private Color RandomColor()
    return colors[rand.Next(0, colors.Length)];

This code creates a Random object and initializes an array of Color values. The RandomColor method uses the Random object to pick a Color from the array and returns it.

The following code shows how the program draws the text’s characters.

// Make CharacterRanges to indicate which
// ranges we want to measure.
CharacterRange[] ranges = new CharacterRange[txt.Length];
for (int i = 0; i < txt.Length; i++)
    ranges[i] = new CharacterRange(i, 1);

// Measure the text to see where each character range goes.
Region[] regions =
        txt, the_font, this.ClientRectangle,

// Draw the characters one at a time.
for (int i = 0; i < txt.Length; i++)
    // See where this character would be drawn.
    RectangleF rectf = regions[i].GetBounds(e.Graphics);
    Rectangle rect = new Rectangle(
        (int)rectf.X, (int)rectf.Y,
        (int)rectf.Width, (int)rectf.Height);

    // Make a brush with a random color.
    using (Brush the_brush = new SolidBrush(RandomColor()))
        // Draw the character.
        e.Graphics.DrawString(txt.Substring(i, 1),
            the_font, the_brush, rectf, string_format);

The code first measures the characters’ positions and then loops through the characters. It makes a rectangle representing each character’s position, creates a brush that uses a random color, and then draws the character with that brush.

Download Example   Follow me on Twitter   RSS feed

This entry was posted in drawing, fonts, graphics, strings and tagged , , , , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Draw text in random colors in C#

  1. random images

    […]BLOG.CSHARPHELPER.COM: Draw text with each character in a random color in C#[…]

  2. Pingback: Draw text filled with random colored lines in C# -

Comments are closed.