计算一个点是否落在多边形内
1 public struct Point 2 { 3 public float x; 4 5 public float y; 6 } 7 8 public class PolygonHelper 9 { 10 /// <summary> 11 /// 判断目标点是否在多边形内 12 /// </summary> 13 /// <param name="targetPoint">目标点</param> 14 /// <param name="polygonPoints">多边形点集合</param> 15 /// <returns></returns> 16 public static bool IsInPolygon(Point targetPoint, List<Point> polygonPoints) 17 { 18 if (polygonPoints == null || polygonPoints.Count < 2) return false; 19 int ncross = 0; 20 for (int i = 0; i < polygonPoints.Count; i++) 21 { 22 Point p1 = polygonPoints[i]; 23 Point p2 = polygonPoints[(i + 1) % polygonPoints.Count]; //相邻两条边p1,p2 24 if (p1.y == p2.y) 25 continue; 26 if (targetPoint.y < Math.Min(p1.y, p2.y)) 27 continue; 28 if (targetPoint.y >= Math.Max(p1.y, p2.y)) 29 continue; 30 double x = (targetPoint.y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y) + p1.x; 31 if (x > targetPoint.x)// 32 ncross++; 33 } 34 return (ncross % 2 == 1); 35 } 36 }