射线法
ispointinpolygon方法用于判断点是否在多边形内部。points表示多边形各点的坐标,point表示要判断的点的坐标
public class PointInPolygon { /** * 判断点是否在多边形内部 * * @param points 各点多边形坐标 * @param point 要判断的点的坐标 * @return true在内部表示,false表示外部 */ public static boolean isPointInPolygon(Point[] points, Point point) { // 判断点是否在多边形顶点上 for (Point p : points) { if (p.x == point.x && p.y == point.y) { return true; } } // 射线法判断 int count = 0; for (int i = 0; i < points.length; i++) { Point p1 = points[i]; Point p2 = points[(i + 1) % points.length]; // 若点在两个顶点的连线上,直接返回true if ((point.x == p1.x && point.y == p1.y) || (point.x == p2.x && point.y == p2.y)) { return true; } // 判断射线与边的交点 if (p1.y == p2.y) { // 若边缘是水平的,不需要考虑 continue; } if (point.y < Math.min(p1.y, p2.y) || point.y >= Math.max(p1.y, p2.y)) { // 若点的纵坐标不在边缘范围内,不需要考虑 continue; } double x = (double) (point.y - p1.y) * (double) (p2.x - p1.x) / (double) (p2.y - p1.y) + p1.x; if (x > point.x) { // 若交点在射线右侧,则统计 count++; } } return count % 2 == 1; // 判断统计交点数,奇数在内部,偶数在外面 } public static void main(String[] args) { Point[] points = new Point[]{new Point(0, 0), new Point(2, 0), new Point(2, 2), new Point(1, 3), new Point(0, 2)}; Point point = new Point(1, 1); boolean result = isPointInPolygon(points, point); System.out.println(result); // true }}class Point { int x; int y; public Point(int x, int y) { this.x = x; this.y = y; }}