We help IT Professionals succeed at work.

Drawing a <blank>agon

Clif asked
Here's an interesting question...

Is it possible to draw a multi-faceted "circle" given a diameter (or radius) and a number of sides?

Basically, if I gave a diameter of 150px and 8 sides, I'd get this (the blue shape, not the grey shape):
Code or link to sample, please (in VB.Net).

Watch Question

Most Valuable Expert 2012
Top Expert 2014

High School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
Top Expert 2009
This is basic Trig...   =)
Public Class Form1

    Private Radius As Integer = 150
    Private NumberSides As Integer = 8

    Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
        Dim center As New Point(Me.ClientRectangle.Width / 2, Me.ClientRectangle.Height / 2)

        Dim rc As New Rectangle(center, New Size(1, 1))
        rc.Inflate(Radius, Radius)
        e.Graphics.DrawEllipse(Pens.Black, rc)

        e.Graphics.DrawPolygon(Pens.Blue, GetPolygon(center, Radius, NumberSides))
    End Sub

    Private Function GetPoint(ByVal center As Point, ByVal angleInDegrees As Single, ByVal distance As Single) As Point
        Dim angleInRads = (angleInDegrees - 90) * Math.PI / CSng(180)
        Return New Point(center.X + distance * Math.Cos(angleInRads), center.Y + distance * Math.Sin(angleInRads))
    End Function

    Private Function GetPolygon(ByVal center As Point, ByVal radius As Single, ByVal sides As Integer) As Point()
        Dim points As New List(Of Point)
        Dim Angle As Single = CSng(360) / CSng(NumberSides)
        For i As Integer = 0 To NumberSides - 1
            points.Add(GetPoint(center, CSng(i) * Angle, radius))
        Return points.ToArray
    End Function

End Class

Open in new window


That works perfectly.