Graphics.DrawPolygon绘制六边形?

时间:2012-08-20 23:16:49

标签: .net graphics

我正在使用一些简单的代码绘制六边形,我得到了意想不到的结果。

代码如下:

Public Class Form1

Dim bm As New Bitmap(640, 480)
Dim bmg As Graphics = Graphics.FromImage(bm)
Dim p As Pen = New Pen(Color.Black)
Dim sb As SolidBrush = New SolidBrush(Color.Black)


Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    DrawHex(80, 50)
End Sub

Public Sub DrawHex(x As Integer, y As Integer)

    Dim side As Integer = 25  '' the length of the side of a hex

    Dim ShortSide As Single = Convert.ToSingle(System.Math.Sin(30 * System.Math.PI / 180) * side)
    Dim LongSide As Single = Convert.ToSingle(System.Math.Cos(30 * System.Math.PI / 180) * side)

    Dim Points(6) As PointF
    Points(0) = New PointF(x, y)
    Points(1) = New PointF(x + side, y)
    Points(2) = New PointF(x + side + ShortSide, y + LongSide)
    Points(3) = New PointF(x + side, y + LongSide + LongSide)
    Points(4) = New PointF(x, y + LongSide + LongSide)
    Points(5) = New PointF(x - ShortSide, y + LongSide)
    bmg.DrawPolygon(p, Points)

End Sub

Private Sub Form1_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint

    e.Graphics.DrawImage(bm, New Point(10, 10))

End Sub

结束班

六角形的五个点很好。这是最后一点没有正确绘制,我不明白为什么:

enter image description here

“ShortSide”和“LongSide”表示六边形外部的直角三角形线。我很确定数学是正确的,我觉得我错过了一些明显的东西。

谢谢!

1 个答案:

答案 0 :(得分:2)

数组基于零。将其更改为:

Dim Points(5) As PointF

会得到6分。你的最后一点(#7)默认为(0,0)。