     Home
Search

What's New
Index
Books
Q & A
Banners

Feedback
Tip Jar     MSDN Visual Basic Community   Title Determine whether a point is inside a polygon polygon, point, inside, contains Graphics 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 X As Single, ByVal Y _
As Single, ByVal num_polygon_points As Integer, _
polygon_points() As POINTAPI) As Boolean
Dim pt As Integer
Dim total_angle As Single

' Get the angle between the point and the
' first and last vertices.
total_angle = GetAngle( _
polygon_points(num_polygon_points).X, _
polygon_points(num_polygon_points).Y, _
X, Y, _
polygon_points(1).X, polygon_points(1).Y)

' Add the angles from the point to each other
' pair of vertices.
For pt = 1 To num_polygon_points - 1
total_angle = total_angle + GetAngle( _
polygon_points(pt).X, polygon_points(pt).Y, _
X, Y, _
polygon_points(pt + 1).X, polygon_points(pt + _
1).Y)
Next pt

' 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.
PointInPolygon = (Abs(total_angle) > PI)
End Function```

For more information on graphics programming in Visual Basic, see my book Visual Basic Graphics Programming.  Copyright © 1997-2003 Rocky Mountain Computer Consulting, Inc.   All rights reserved.  Updated 