BLOG.CSHARPHELPER.COM: Determine whether a point is inside a polygon in C#
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); }
Great code man, worked like a charm for me. I was having a problem with the code from http://social.msdn.microsoft.com/forums/en-US/winforms/thread/95055cdc-60f8-4c22-8270-ab5f9870270a/ because its was saying that a point is inside when i used a very complex polygon, and with your code it worked very well, thank you so much.
Reply to this
Thank you!
Great applicaton :))
Reply to this
great application thank you!
Reply to this