import java.util.ArrayList; import java.util.List; public class GeometryUtil { /** * 获取点与直线之间的距离 * @param p 点 * @param a 直线上一点 * @param b 直线上一点 * @return */ public static double pointToLineDist(Point p,Point a,Point b) { double ABx = b.x - a.x; double ABy = b.y - a.y; double APx = p.x - a.x; double APy = p.y - a.y; double AB_AP = ABx * APx + ABy * APy; double distAB2 = ABx * ABx + ABy * ABy; double Dx = a.x, Dy = a.y; if (distAB2 != 0) { double t = AB_AP / distAB2; if (t >= 1) { Dx = b.x; Dy = b.y; } else if (t > 0) { Dx = a.x + ABx * t; Dy = a.y + ABy * t; } else { Dx = a.x; Dy = a.y; } } double PDx = Dx - p.x, PDy = Dy - p.y; return Math.sqrt(PDx * PDx + PDy * PDy); }
/** * 获取点与多边形之间最近距离 * @param point * @param points * @return 0.0 :点位于多边形内部 >0.0 : 点与多边形之间的最近距离 */
public static double pintoToPolygonMinDist(Point point, List<Point> points) { double dist = Double.MAX_VALUE; int N = points.size(); for (int i = 0, j = N - 1; i < N; j = i++) { dist = Math.min(dist, pointToLineDist(point, points.get(i), points.get(j))); } return dist; } }
补充一种点到直线距离
补充一种点到直线距离 /** * 获取点与直线之间的距离 * * @param P3 点 * @param PA 直线上一点 * @param PB 直线上一点 * @return */ static double GetNearestDistance(Point P3,Point PA, Point PB) { //----------图2-------------------- double a, b, c; a = GetPointDistance(PB, P3); if (a <= 0.0000001) return 0.0d; b = GetPointDistance(PA, P3); if (b <= 0.0000001) return 0.0d; c = GetPointDistance(PA, PB); if (c <= 0.0000001) return a;//如果PA和PB坐标相同,则退出函数,并返回距离 //------------------------------ if (a * a >= b * b + c * c)//--------图3-------- return b; //如果是钝角返回b if (b * b >= a * a + c * c)//--------图4------- return a; //如果是钝角返回a //图1 double l = (a + b + c) / 2; //周长的一半 double s = Math.sqrt(l * (l - a) * (l - b) * (l - c)); //海伦公式求面积,也可以用矢量求 return 2 * s / c; }
可参考 https://blog.csdn.net/lumingsgtc/article/details/82589211?utm_source=blogxgwz6