Draw a non-intersecting star in C#

The NonIntersectingStarPoints function generates the points needed to draw a non-intersecting star and returns them in an array.

// Return PointFs to define a non-intersecting star.
private PointF[] NonIntersectingStarPoints(
int num_points, Rectangle bounds)
{
// Make room for the points.
PointF[] pts = new PointF[2 * num_points];

double rx1 = bounds.Width / 2;
double ry1 = bounds.Height / 2;
double rx2 = rx1 * 0.5;
double ry2 = ry1 * 0.5;
double cx = bounds.X + rx1;
double cy = bounds.Y + ry1;

// Start at the top.
double theta = -Math.PI / 2;
double dtheta = Math.PI / num_points;
for (int i = 0; i < 2 * num_points; i += 2)
{
pts[i] = new PointF(
(float)(cx + rx1 * Math.Cos(theta)),
(float)(cy + ry1 * Math.Sin(theta)));
theta += dtheta;

pts[i + 1] = new PointF(
(float)(cx + rx2 * Math.Cos(theta)),
(float)(cy + ry2 * Math.Sin(theta)));
theta += dtheta;
}

return pts;
}

The function allocates room for two PointFs for each of the star's points, one for the point and one for the inside corner next to the point. It then uses a loop to generate the PointFs. The variable theta determines the direction of each point form the center of the star. For each theta value, the program creates the point and the neighboring inside corner.

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

// Draw a non-intersecting star.
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

PointF[] pts = NonIntersectingStarPoints(7, 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.