为什么这段代码:
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 坐标相距很远,而且它们不相交。我把它们画在一个 Swing 板上,它们是分开的,但看起来它们是共线的。这是问题吗? 我尝试测试简单的共线(如 (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
关于java - Java 中 Line2D 的 intersectsLine 输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27410258/