标签:style class blog code java http
如何判断一个点在多边形内还是多边形外,最常见的方法就是射线法,原理就是,从点P开始,做一条任意的射线,如果射线与多边形边的交点个数为偶数个则表明点在多边形外,交点个数为奇数个时则表明点在多边形内。如果点在多边形内部时,无论如何画射线都会有交点,且为奇数个。如下图:
1 public static bool InsidePolygon(List<Point> polygon, Point p) 2 { 3 if (polygon.Count <= 0) 4 return false; 5 int counter = 0; 6 int i; 7 double xinters; 8 Point p1 = polygon[0], p2; 9 int N = polygon.Count; 10 11 for (i = 1; i <= N; i++) 12 { 13 p2 = polygon[i % N]; 14 if (p1.Y != p2.Y && p.Y > Math.Min(p1.Y, p2.Y) && p.Y <= Math.Max(p1.Y, p2.Y) && p.X <= Math.Max(p1.X, p2.X)) 15 { 16 if (p1.X == p2.X) 17 counter++; 18 else 19 { 20 xinters = (p.Y - p1.Y) * (p2.X - p1.X) / (p2.Y - p1.Y) + p1.X; 21 if (p.X <= xinters) 22 counter++; 23 } 24 } 25 p1 = p2; 26 } 27 return (counter % 2) != 0; 28 }
注:
1. 多边形不区分内多边形和外多边形,都适用
2. 点的坐标在左手坐标系和右手坐标系下都适用
标签:style class blog code java http
原文地址:http://www.cnblogs.com/anthonyBlog/p/3783890.html