c# radial gradient brush effect in GDI and winforms

ClimberM picture ClimberM · Aug 19, 2010 · Viewed 16.2k times · Source

I have created a c# windows application and written 75% of the code. The program allows the user to create a flow chart, and will shade the flow chart shapes according to their status. I wanted them to become 3d buttons such as Gel Button from the website Webdesign.org

Rather than create a PNG for each button, I wanted to create them in C# using brushes or other technique, such as:

// Create solid brush.
SolidBrush blueBrush = new SolidBrush(Color.Blue);
// Create points that define polygon.
PointF point1 = new PointF(50.0F, 50.0F);
PointF point2 = new PointF(100.0F, 25.0F);
PointF point3 = new PointF(200.0F, 5.0F);
PointF point4 = new PointF(250.0F, 50.0F);
PointF point5 = new PointF(300.0F, 100.0F);
PointF point6 = new PointF(350.0F, 200.0F);
PointF point7 = new PointF(250.0F, 250.0F);
PointF[] curvePoints = {point1, point2, point3, point4, point5, point6, point7};
// Define fill mode.
FillMode newFillMode = FillMode.Winding;
// Fill polygon to screen.
e.Graphics.FillPolygon(blueBrush, curvePoints, newFillMode);

I know WPF has radial gradients, but can I do something simular in CGI?

Answer

Drew Noakes picture Drew Noakes · Nov 29, 2012

Unlike WPF, GDI+/WinForms does not have a RadialGradientBrush. However you can achieve the same effect using a PathGradientBrush.

Here's an example:

Rectangle bounds = ...;
using (var ellipsePath = new GraphicsPath())
{
    ellipsePath.AddEllipse(bounds);
    using (var brush = new PathGradientBrush(ellipsePath))
    {
        brush.CenterPoint = new PointF(bounds.Width/2f, bounds.Height/2f);
        brush.CenterColor = Color.White;
        brush.SurroundColors = new[] { Color.Red };
        brush.FocusScales = new PointF(0, 0);

        e.Graphics.FillRectangle(brush, bounds);
    }
}

The PathGradientBrush has lots of properties to experiment with to ensure you get the effect you're after.