测试两个矩形是否相交的快速方法是什么?
在互联网上搜索得到了这句话(WOOT!),但我不知道如何用Javascript编写它,它似乎是用一种古老的C++形式编写的。
struct
{
LONG left;
LONG top;
LONG right;
LONG bottom;
} RECT;
bool IntersectRect(const RECT * r1, const RECT * r2)
{
return ! ( r2->left > r1->right
|| r2->right < r1->left
|| r2->top > r1->bottom
|| r2->bottom < r1->top
);
}
发布于 2010-05-02 11:50:26
这就是如何将代码转换为JavaScript。请注意,正如评论所建议的那样,您的代码和文章的代码中都有一个拼写错误。具体地说,r2->right left
应该是r2->right < r1->left
,r2->bottom top
应该是r2->bottom < r1->top
,函数才能工作。
function intersectRect(r1, r2) {
return !(r2.left > r1.right ||
r2.right < r1.left ||
r2.top > r1.bottom ||
r2.bottom < r1.top);
}
测试用例:
var rectA = {
left: 10,
top: 10,
right: 30,
bottom: 30
};
var rectB = {
left: 20,
top: 20,
right: 50,
bottom: 50
};
var rectC = {
left: 70,
top: 70,
right: 90,
bottom: 90
};
intersectRect(rectA, rectB); // returns true
intersectRect(rectA, rectC); // returns false
发布于 2010-05-02 11:42:54
function intersect(a, b) {
return (a.left <= b.right &&
b.left <= a.right &&
a.top <= b.bottom &&
b.top <= a.bottom)
}
这假设top
通常小于bottom
(即y
坐标向下增加)。
发布于 2014-04-08 03:18:01
这就是.NET框架实现Rectangle.Intersect的方式
public bool IntersectsWith(Rectangle rect)
{
if (rect.X < this.X + this.Width && this.X < rect.X + rect.Width && rect.Y < this.Y + this.Height)
return this.Y < rect.Y + rect.Height;
else
return false;
}
或者静态版本:
public static Rectangle Intersect(Rectangle a, Rectangle b)
{
int x = Math.Max(a.X, b.X);
int num1 = Math.Min(a.X + a.Width, b.X + b.Width);
int y = Math.Max(a.Y, b.Y);
int num2 = Math.Min(a.Y + a.Height, b.Y + b.Height);
if (num1 >= x && num2 >= y)
return new Rectangle(x, y, num1 - x, num2 - y);
else
return Rectangle.Empty;
}
https://stackoverflow.com/questions/2752349
复制相似问题