[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: Draw a star in C#

draw a star

The following StarPoints method generates the points needed to draw a star and returns them in an array.

// Return PointFs to define a star. private PointF[] StarPoints(int num_points, Rectangle bounds) { // Make room for the points. PointF[] pts = new PointF[num_points]; double rx = bounds.Width / 2; double ry = bounds.Height / 2; double cx = bounds.X + rx; double cy = bounds.Y + ry; // Start at the top. double theta = -Math.PI / 2; double dtheta = 4 * Math.PI / num_points; for (int i = 0; i < num_points; i++) { pts[i] = new PointF( (float)(cx + rx * Math.Cos(theta)), (float)(cy + ry * Math.Sin(theta))); theta += dtheta; } return pts; }

The method allocates room for the points and then uses a loop to generate them. The variable theta determines the direction of each point with respect to the center of the star. If the star's center has coordinates (cx, cy), then a point on the star has coordinates:

(cx + rx × cos(theta), cy + ry × sin(theta))

If the code were drawing a regular polygon with num_points sides, then the difference between adjacent theta values would be 2 × π / num_points. In this method, dtheta is twice that value so the lines drawing the star skip polygon points much as you probably do when you draw a five-pointed star. (Note that this only works for stars with an odd number of points. Later posts explore other options.)

The following code shows how the program draws the star.

// Draw a star. private void Form1_Paint(object sender, PaintEventArgs e) { e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; PointF[] pts = StarPoints(5, this.ClientRectangle); e.Graphics.DrawPolygon(Pens.Blue, pts); }

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

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