BLOG.CSHARPHELPER.COM: Fill an area with an elliptical gradient in C#
Fill an area with an elliptical gradient in C#
The normal Windows Forms .NET Framework libraries don't include a RadialGradientBrush class. Such a class is included in the System.Windows.Media namespace, but that namespace is intended for use by WPF (Windows Presentation Foundation) windows and is hard to use in Windows Forms applications. Fortunately the PathGradientBrush can do the job.
The following Paint event handler shows how this example fills the form with an elliptical gradient.
// 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 fro every point, the brush uses the final color for any remaining points. In this example, the array contains only one color so the brush uses it for all of the path's points.
Finally the program fills the ellipse defined by the Rectangle using the brush.
Comments