Answer the question
In order to leave comments, you need to log in
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
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)));
}
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 questionAsk a Question
731 491 924 answers to any question