如何检查2条线段是否相交? [英] How to check whether 2 lines segments intersect?

查看:72
本文介绍了如何检查2条线段是否相交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查两个线段L1(p1,p2)和L2(p3,p4)是否相交?我不需要相交点,我只需要知道它们是否相交即可.由于我的应用程序对此进行了大量计算,因此我需要找到一个快速的解决方案.

How do I check whether 2 line segments, L1(p1,p2) and L2(p3,p4), intersect with each other? I do not need the intersection point, I just need to know whether they intersect or not. Since my application calculating this a lot, I need to find a fast solution.

谢谢

推荐答案

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

To test whether two line segments intersect, you can use Java's 2D API, specifically the methods of 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));

如果您有兴趣了解代码的工作方式,以查看是否可以在特定域中更快地进行编码,可以查看

If you are interested in finding out how the code works, in order to see if you can make it faster in your specific domain, you can check out the code for OpenJDK implementation. But remember, always profile before you optimize; it is probably plenty fast enough as it is.

这篇关于如何检查2条线段是否相交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆