如何检查直线的任何点(或部分)是否在矩形内部或接触矩形
我想检查一条线(或线的任何点)是否在矩形内或与矩形相交。
我有 (x0, y0) 和 (x1, y1) 作为一条线的起点和终点。 另外,(ax,ay)和(bx,by)作为矩形的左上角和右下角
例如,
____________
| |
---|----- | Result: true
| |
|____________|
/
_/__________
|/ |
/ | Result: true
/| |
|____________|
____________
| |
| -------- | Result: true
| |
|____________| ---------- Result: false
有人可以建议如何做到这一点吗?我不想知道那是哪一点,我只想知道它是否存在。
非常感谢您的帮助
I want to check if a line (or any point of a line) is within a rectangle or intersects a rectangle.
I have (x0, y0) and (x1, y1) as starting and ending points of a line.
Also, (ax,ay) and (bx,by) as the top-left and bottom-right points of a rectangle
For example,
____________
| |
---|----- | Result: true
| |
|____________|
/
_/__________
|/ |
/ | Result: true
/| |
|____________|
____________
| |
| -------- | Result: true
| |
|____________| ---------- Result: false
Can anyone suggest how to do this? I dont want to know which point is that, i just want to know if its there or not.
Thanks a lot for help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一种和第三种情况很简单——如果线的任一端点在框内(即> ax 和ay,< bx 和by),则简单地返回true。
第二个提出了一个问题 - 我们不能再依赖线路的端点。在这种情况下,我们必须测试矩形每条边的线。
我们的直线方程为 (x1 - x0)*x + (y1 - y0)*y + x0*y0 - x1*y1 = 0 ,我们可以为每一边构造一个类似的方程使用角点绘制矩形。接下来,将矩形边的方程代入我们的直线将得到交集。
最后,我们检查以确保该点位于矩形边的边界内,并且同样位于我们正在考虑的线段内。
此讨论对此有更详细的说明。
The first and third cases are trivial - simply return true if either endpoint of the line is within the box (i.e. > ax and ay, < bx and by).
The second presents a problem - we can't rely on the endpoints of our line anymore. In this case, we will have to test the line with each edge of the rectangle.
The equation for our line will be
(x1 - x0)*x + (y1 - y0)*y + x0*y0 - x1*y1 = 0
, and we can construct a similar equation for each side of the rectangle using the corners. Following that, substituting the equation for the sides of the rectangle into our line will give us the intersection.Finally, we check to ensure that the point is within the bounds of the side of the rectangle, and likewise within the line segment we are considering.
There is a more detailed account of this in this discussion.