BLOG.CSHARPHELPER.COM: Draw a background with a moving color gradient in C#
Draw a background with a moving color gradient in C#
When the form's Timer fires, the event handler refreshes the PictureBox.
// Make the PictureBox redraw. private void tmrRefresh_Tick(object sender, EventArgs e) { picCanvas.Refresh(); }
The PictureBox's Paint event handler uses the following code to draw the background and text on top of it.
// Draw the background with text on top. private void picCanvas_Paint(object sender, PaintEventArgs e) { // Draw the background gradient. 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.White, Color.Blue}; color_blend.Positions = new float[] {0, Middle, 1}; br.InterpolationColors = color_blend; e.Graphics.FillRectangle(br, ClientRectangle); }
// Change the gradient's midpoint. Middle += Delta; if ((Middle > 1) || (Middle < 0)) Delta = -Delta;
// Draw some text. using (StringFormat string_format = new StringFormat()) { string_format.Alignment = StringAlignment.Center; string_format.LineAlignment = StringAlignment.Center; e.Graphics.DrawString("Moving Gradient", this.Font, Brushes.Black, picCanvas.ClientSize.Width / 2, picCanvas.ClientSize.Height / 2, string_format); } }
The code creates a LinearGradientBrush. It defines a color blend to make the brush shade from red to white to blue. It sets the positions of the colors so red and blue are at the ends and green is positioned according to the variable Middle.
The program fills the PictureBox with the brush and then updates Middle so the white part will be in a different position next time. If Middle moves beyond 0 or 1, the program changes the sign of Delta, the amount by which it adjusts Middle, so the movement goes in the other direction next time.
Finally the program draws some text over the colored background.
Comments