Draw a star in C#

The StarPoints function 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 function allocates room for the points and then uses a loop to generate them. The variable theta determines the direction of each point from the center of the star. If the code were drawing a regular polygon with num_points sides, then the difference between adjacent theta values would be 2 * Pi / num_points. In this function, dtheta is twice that 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.)

The program uses this function as shown in the following code.

// 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);
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.