使用线段相交公式计算出两条线段是否相交: //线段相交公式 public static boolean segmentIntersection(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { float d = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); if (d == 0) return false; float ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / d; float ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / d; if (ua < 0 || ua > 1 || ub < 0 || ub > 1) return false; return true; } //使用示例 boolean isIntersect = segmentIntersection(x1, y1, x2, y2, x3, y3, x4, y4);
计算出两条线段的交点: //计算线段交点 public static PointF getIntersectionPoint(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { float d = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); if (d == 0) return null; PointF intersection = new PointF(); intersection.x = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / d; intersection.y = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / d; return intersection; } //使用示例 PointF intersectionPoint = getIntersectionPoint(x1, y