要测试两个线段是否相交,可以使用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 loopSystem.out.println(Line2D.linesIntersect(100,100,200,200,150,150,150,200));
如果您有兴趣了解代码的工作方式,以便查看是否可以在特定域中更快地进行编码,可以查看OpenJDK实现的代码。但是请记住,在进行优化之前,请务必先进行分析;它可能足够快。



