BLOG.CSHARPHELPER.COM: Fill text with a moving color gradient in C#
Fill text with a moving color gradient in C#
This example uses the following code to draw text that is shaded with a moving color gradient.
// The position for the middle of the color gradient.
private float Middle = 0f;
// The amount by which to move Middle each tick.
private float Delta = 0.1f;
// Redraw.
private void tmrRotate_Tick(object sender, EventArgs e)
{
picCanvas.Invalidate();
}
// Draw the text.
private void picCanvas_Paint(object sender, PaintEventArgs e)
{
e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
// Make the gradient brush.
using (LinearGradientBrush br = new LinearGradientBrush(
new Point(0, 0), new Point(ClientSize.Width, 0), Color.Red, Color.Blue))
{
ColorBlend color_blend = new ColorBlend();
color_blend.Colors = new Color[] {Color.Red, Color.Lime, Color.Blue};
color_blend.Positions = new float[] {0f, Middle, 1f};
br.InterpolationColors = color_blend;
// Fill some text with it.
using (StringFormat string_format = new StringFormat())
{
string_format.Alignment = StringAlignment.Center;
string_format.LineAlignment = StringAlignment.Center;
e.Graphics.DrawString("Gradient Text", this.Font, br, picCanvas.ClientRectangle, string_format);
}
}
// Adjust the gradient's midpoint.
Middle += Delta;
if ((Middle > 1) || (Middle < 0)) Delta = -Delta;
}
Variable Middle indicates the point in the color gradient between 0.0 and 1.0 where the center color of the gradient should be drawn. Delta is the amount of change in the value Middle the program uses when the program's Timer ticks.
When a Tick occurs (every 100 milliseconds or 10 times per second), the Tick event handler invalidates the picCanvas PictureBox so its Paint event executes.
The Paint event makes a horizontal LinearGradientBrush with blend colors red, lime, and blue. The blend's Positions array determines where in the blend the colors appear. In this program red occurs on the left at 0.0. lime occurs at the value Middle, and blue occurs on the right at 1.0.
The program then creates a StringFormat to center the text adds draws the text using the gradient brush.
You can use similar techniques to make other changing brushes. For example, you could use a radial gradient brush and move the brush's center back and forth or in a circle within the text.
Comments