[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[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]

[C# 5.0 Programmer's Reference]

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

Title: Fill a polygon with a PathGradientBrush in C#

example

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 the example to experiment with it and to see additional details.

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