如何检查2个线段是否相交?

如何检查2个线段L1(p1,p2)和L2(p3,p4)是否相互交叉? 我不需要交叉点,我只需要知道它们是否相交。 由于我的应用程序计算了很多,我需要找到一个快速的解决方案。

谢谢

要测试两个线段是否相交,可以使用Java的2D API,特别是Line2D的方法。

Line2D line1 = new Line2D.Float(100, 100, 200, 200); Line2D line2 = new Line2D.Float(150, 150, 150, 200); boolean result = line2.intersectsLine(line1); System.out.println(result); // => true // Also check out linesIntersect() if you do not need to construct the line objects // It will probably be faster due to putting less pressure on the garbage collector // if running it in a loop System.out.println(Line2D.linesIntersect(100,100,200,200,150,150,150,200)); 

如果您有兴趣了解代码的工作原理,那么为了了解您是否可以在特定域中加快代码 ,您可以查看OpenJDK实现的代码 。 但请记住,在优化之前始终要进行配置; 这可能足够快了。

我只是使用为你做的方法,或者如果你想重新实现它,请查看它的源代码: Line2D.linesIntersect()