Determine whether a point is inside a polygon in C#

One way to determine whether a point lies within a polygon is to add up the angles between the point 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 bool PointInPolygon(float X, float Y)
{
// Get the angle between the point and the
// first and last vertices.
int max_point = Points.Length - 1;
float total_angle = 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 (int i = 0; i < max_point; i++)
{
total_angle += GetAngle(
Points[i].X, Points[i].Y,
X, Y,
Points[i + 1].X, Points[i + 1].Y);
}

// 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);
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.