如何检查线的任何点(或部分)是否在内部或接触矩形 [英] How to check if any point (or part) of a line is inside or touches a rectangle

查看:78
本文介绍了如何检查线的任何点(或部分)是否在内部或接触矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查一条线(或一条线的任何点)是否在矩形内或与矩形相交.

I want to check if a line (or any point of a line) is within a rectangle or intersects a rectangle.

我以(x0,y0)和(x1,y1)作为直线的起点和终点. 另外,(ax,ay)和(bx,by)是矩形的左上角和右下角

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

例如,

     ____________
    |            |
 ---|-----       |    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.

非常感谢您的帮助

推荐答案

第一种和第三种情况很简单-如果该行的任一端点在该框内(即> ax和ay,< bx和by ).

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.

这条线的等式为(x1 - x0)*x + (y1 - y0)*y + x0*y0 - x1*y1 = 0,我们可以使用角为矩形的每一侧构造一个类似的等式.然后,将矩形的边的等式代入我们的线中将得到相交.

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.

此讨论.

这篇关于如何检查线的任何点(或部分)是否在内部或接触矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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