射线法
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;
}
}
标签:p2,判断,多边形,point,Point,射线,p1,new,points
From: https://blog.51cto.com/u_16085354/6458440