BLOG.CSHARPHELPER.COM: Draw text with each character in a random color in C#
Draw text with each character in a random color in C#
The example Use MeasureCharacterRanges to see where the parts of a string will be drawn in C# shows how to determine where the characters in a string will be drawn and then draws them individually. This example uses similar code but it draws each character in a randomly selected color.
The following code shows how the program draws each character.
// 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); }
This code creates a solid brush using the Color returned by the RandomColor method. It then uses that brush to draw the character.
The following code shows the RandomColor method.
// Return a random color. private Random rand = new Random(); private Color[] colors = { Color.Red, Color.Green, Color.Blue, Color.Lime, Color.Orange, Color.Fuchsia, }; private Color RandomColor() { return colors[rand.Next(0, colors.Length)]; }
The code declares and initializes a Random object and an array of Color values. The RandomColor method itself simply picks a random color from the array.
Comments