A
A
Artur Panteleev2013-12-13 19:25:34
Programming
Artur Panteleev, 2013-12-13 19:25:34

How to draw a regular C# polygon?

Hello everyone, it became necessary to write a function that draws a regular polygon inscribed in a circle. The function takes the number of vertices (from 3 to infinity, + the radius of the circumscribed circle around the polygon). You can only use standard components, i.e. draw on the PictureBox using the Graphics class. So far I can not think of a universal way for the n-gon.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya Glebov, 2013-12-14
@arturpanteleev

My version

private void Form1_Paint(object sender, PaintEventArgs e) {
  DrawRegularPolygon(new PointF(100, 100), 10, 100, e.Graphics);
}

private static void DrawRegularPolygon(PointF center, // Координаты центра окружности
   int vertexes, // Количество вершин
   float radius, // Радиус
   Graphics graphics) {
  var angle = Math.PI*2/vertexes;

  var points = Enumerable.Range(0, vertexes)
        .Select(i => PointF.Add(center, new SizeF((float) Math.Sin(i*angle)*radius, (float) Math.Cos(i*angle)*radius)));

   graphics.DrawPolygon(Pens.Black, points.ToArray());
   graphics.DrawEllipse(Pens.Aqua, new RectangleF(PointF.Subtract(center, new SizeF(radius, radius)), new SizeF(radius * 2, radius * 2)));
}

I
Igor_Sib, 2013-12-14
@Igor_Sib

To get the vertices - from the starting point you set aside a segment with a radius R, say to the right - this is the first vertex, then you turn by an angle (360 / N, where N is the number of angles), you get the coordinates of the second vertex, then you turn the same amount - you get the coordinates of the third , etc. I would do so.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question