要测试两个线段是否相交,可以使用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));
如果您有兴趣了解代码的工作原理,为了了解您是否可以在特定域中加快代码,可以查看the code for OpenJDK implementation.但请记住,在优化之前始终要进行配置;这可能足够快了.