为什么这段代码:
Line2D line1 = new Line2D.Double(464.9298111721873, 103.78661133348942, 684.8391765253534, -155.44752172931908);
Line2D line2 = new Line2D.Double(414.16903384086487, 163.62456359144306, 393.52528378472925, 187.95988300984624);
line1.intersectsLine(line2);
回归真的吗?
显然,线的x坐标是分开的,它们不相交.我将它们画在一个秋千面板上,它们是分开的,但看起来它们是共线的.这是问题吗?
我尝试在简单的共线上进行测试(如(1,3,4,3),(6,3,8,3)),它看起来很好用.
最佳答案
Java Docs说Line2D类的方法:
public boolean intersects(double x, double y, double w, double h)
测试Shape的内部是否与指定的矩形区域的内部相交.它使用Shape.intersects()方法,但准确确定此交集的计算非常昂贵.
这意味着对于某些Shapes,即使矩形区域不与Shape相交,此方法也可能返回true.
虽然您使用的是itersectsLine()方法,但intersects()和intersectsLine()都使用表面下方相同的昂贵方法.该方法称为linesIntersect(),在第298行是specified here
Area类比大多数Shape对象执行更精确的几何交集计算,因此如果需要更精确的答案,则可以使用它.例如:
boolean intersectionExists(Shape shape1, Shape shape2) {
Area area1 = new Area(shape1);
area1.intersect(new Area(shape2));
return !area1.isEmpty();
}
使用您的值进行测试:
public static void main(String[] args) {
Line2D line1 = new Line2D.Double(464.9298111721873, 103.78661133348942, 684.8391765253534, -155.44752172931908);
Line2D line2 = new Line2D.Double(414.16903384086487, 163.62456359144306, 393.52528378472925, 187.95988300984624);
System.out.println("Lines intersect? " + intersectionExists(line1, line2));
}
输出:
Lines intersect? false