[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Fill an area with an elliptical gradient in C#


Filling an area with an elliptical gradient is non-trivial in a Windows Forms application because the .NET Framework libraries intended for use with Windows Forms don't include a RadialGradientBrush class. There is such a class in the System.Windows.Media namespace, but that namespace is intended for use by WPF (Windows Presentation Foundation) and is hard to use in Windows Forms applications. Fortunately with a little extra work the PathGradientBrush class can do the job.

The following Paint event handler shows how this example fills the form with an elliptical gradient.

// Draw the elliptical gradient background. private void Form1_Paint(object sender, PaintEventArgs e) { e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; // Make a GraphicsPath to represent the ellipse. Rectangle rect = new Rectangle( 10, 10, this.ClientSize.Width - 20, this.ClientSize.Height - 20); GraphicsPath path = new GraphicsPath(); path.AddEllipse(rect); // Make a PathGradientBrush from the path. using (PathGradientBrush br = new PathGradientBrush(path)) { br.CenterColor = Color.Blue; br.SurroundColors = new Color[] { this.BackColor }; e.Graphics.FillEllipse(br, rect); } }

The code creates a Rectangle to represent the area where the brush will be defined. It then creates a GraphicPath object and adds an ellipse to it, using the Rectangle to define the ellipse.

Next the code uses the GraphicsPath to create a PathGradientBrush. That brush shades colors from a center point to the points along the path. By default, the center point lies in the center of a symmetric path such as the ellipse used here, so the code doesn't need to alter that point.

The code sets the brush's center point color to blue. It then sets the brush's SurroundColors property to an array of the colors that the brush should use for the points along the path. If this array doesn't hold enough colors for every point, the brush repeats the final color for any remaining points. In this example, the array contains only one color (the form's background color), so the brush uses it for all of the path's points.

Finally the program uses the brush to fill the ellipse defined by the Rectangle.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.