|
|
Title | Determine whether a point is inside a polygon in Visual Basic .NET |
Description | This example shows how to determine whether a point is inside a polygon in Visual Basic .NET. |
Keywords | polygon, point, inside, contains, graphics, VB.NET |
Categories | Graphics, VB.NET |
|
|
Add up the angles between the point in question and adjacent points on the polygon taken in order. If the total of all the angles is 2 * PI or -2 * PI, then the point is inside the polygon. If the total is zero, the point is outside. You can verify this intuitively with some simple examples using squares or triangles.
|
|
' Return True if the point is in the polygon.
Public Function PointInPolygon(ByVal points() As PointF, _
ByVal X As Single, ByVal Y As Single) As Boolean
' Get the angle between the point and the
' first and last vertices.
Dim max_point As Integer = points.Length - 1
Dim total_angle As Single = GetAngle( _
points(max_point).X, points(max_point).Y, _
X, Y, _
points(0).X, points(0).Y)
' Add the angles from the point
' to each other pair of vertices.
For i As Integer = 0 To max_point - 1
total_angle += GetAngle( _
points(i).X, points(i).Y, _
X, Y, _
points(i + 1).X, points(i + 1).Y)
Next i
' The total angle should be 2 * PI or -2 * PI if
' the point is in the polygon and close to zero
' if the point is outside the polygon.
Return Math.Abs(total_angle) > 0.000001
End Function
|
|
For more information on graphics programming in Visual Basic, see my book Visual Basic Graphics Programming.
|
|
|
|
|
|