Title: Draw a non-intersecting star in C#
The following NonIntersectingStarPoints method 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 method allocates room for two PointF objects for each of the star's points, one for the point and one for the inside concave corner next to the point. It then uses a loop to generate the PointFs for each point. The variable theta determines the direction of each point with respect to the center of the star. For each theta value, the program creates the point and the neighboring inside corner.
The following code shows how the example progam uses this method to draw a non-intersecting 7-pointed star.
// Draw a star.
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
PointF[] pts = NonIntersectingStarPoints(7, ClientRectangle);
e.Graphics.DrawPolygon(Pens.Blue, pts);
}
Download the example to experiment with it and to see additional details.
|