Fill a polygon with a PathGradientBrush in C#


A PathGradientBrush defines a brush that shades smoothly from a “center point” to specific points along a path. This example fills a hexagon with colors that shade from white in the center to red, yellow, lime, cyan, blue, and magenta at the hexagon’s corners.

The following Paint event handler draws a hexagon filled with a PathGradientBrush.

// Fill a polygon with a PathGradientBrush.
private void Form1_Paint(object sender, PaintEventArgs e)
    // Make the points for a hexagon.
    PointF[] pts = new PointF[6];
    int cx = (int)(this.ClientSize.Width / 2);
    int cy = (int)(this.ClientSize.Height / 2);
    double theta = 0;
    double dtheta = 2 * Math.PI / 6;
    for (int i = 0; i < pts.Length; i++)
        pts[i].X = (int)(cx + cx * Math.Cos(theta));
        pts[i].Y = (int)(cy + cy * Math.Sin(theta));
        theta += dtheta;

    // Make a path gradient brush.
    using (PathGradientBrush path_brush =
        new PathGradientBrush(pts))
        // Define the center and surround colors.
        path_brush.CenterColor = Color.White;
        path_brush.SurroundColors = new Color[] {
            Color.Red, Color.Yellow, Color.Lime,
            Color.Cyan, Color.Blue, Color.Magenta
        // Fill the hexagon.
        e.Graphics.FillPolygon(path_brush, pts);

    // Outline the hexagon.
    e.Graphics.DrawPolygon(Pens.Black, pts);

The code allocates an array to hold points that define a hexagon. It loops through the array creating points offset from the form’s center. The points lie on an ellipse that would touch the form’s four edges. The angle from the center to the first point is 0 radians (to the right). Each point after that is at the angle 2 × π / 6 radians larger than the previous angle.

Next the program uses the points to create a PathGradientBrush. It sets the brush’s center color to white. It sets the brush’s surround colors to an array of colors, one per point defining the hexagon. (By default, the brush’s center point is the center of the points in the path. This program leaves it there but you could move it if you wanted.) The code then uses the brush to fill the polygon.

Download Example   Follow me on Twitter   RSS feed

This entry was posted in graphics and tagged , , , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Fill a polygon with a PathGradientBrush in C#

  1. OperatorX says:


    One small suggestion…

    The following modification will improve the paint behavior of the main form when resizing.

    public Form1()
    this.Load += new System.EventHandler(this.Form1_Load);

    private void Form1_Load(object sender, EventArgs e)
    this.SetStyle(ControlStyles.ResizeRedraw, true);



  2. Rod Stephens says:

    I’ve updated the downloadable example, although I just made a Load event handler at design time. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *