重叠的矩形

本文关键字:重叠 | 更新日期: 2023-09-27 18:07:07

大家好!我有一个这样的例子。我需要写一个方法,它表示如果矩形相互重叠。输入如下:高度,宽度,x-pos和y-pos,矩形平行于x轴和y轴。我使用了问题中的解决方案,我给出了一个链接,但它不能正常工作。它告诉我们矩形即使不重叠也会重叠!我错过了什么重要的东西吗?

代码本身:

    public static bool AreIntersected(Rectangle r1, Rectangle r2)
    {
    return (!(r1.Left > r2.Left + r2.Width) || !(r1.Left + r1.Width < r2.Left) || !(r1.Top < r2.Top - r2.Height)|| !(r1.Top - r1.Height > r2.Top));
    }    

错误画面

这里就可以了

非常感谢您的帮助!

重叠的矩形

答案在您链接的页面上。对代码的唯一更改是将rx.Right替换为rx.Left + rx.Width,将rx.Bottom替换为rx.Top + rx.Height

return !(r1.Left > r2.Left + r2.Width) &&
       !(r1.Left + r1.Width < r2.Left) &&
       !(r1.Top > r2.Top + r2.Height) &&
       !(r1.Top + r1.Height < r2.Top);

然后再一次,我假设你有你自己的Rectangle类你正在使用。如果你使用的是。net矩形结构体,该对象具有RightBottom属性,因此不需要代码替换。

return !(r1.Left > r2.Right) &&
       !(r1.Right < r2.Left) &&
       !(r1.Top > r2.Bottom) &&
       !(r1.Bottom < r2.Top);

当然,你也可以很容易地使用静态矩形。相交的方法。

return !Rectangle.Intersect(r1, r2).IsEmpty;

使用矩形。相交:

public static bool AreIntersected(Rectangle r1, Rectangle r2)
{
    return !Rectangle.Intersect(r1, r2).IsEmpty;
}

如果你不能使用Rectangle.Intersect:

public static bool AreIntersected(Rectangle r1, Rectangle r2)
{
    int x1 = Math.Max(r1.X, r2.X);
    int x2 = Math.Min(r1.X + r1.Width, r2.X + r2.Width); 
    int y1 = Math.Max(r1.Y, r2.Y);
    int y2 = Math.Min(r1.Y + r1.Height, r2.Y + r2.Height); 
    return (x2 >= x1 && y2 >= y1);
}

另一种方法:

public static bool AreIntersected(Rectangle r1, Rectangle r2)
{
    return(r2.X < r1.X + r1.Width) &&
        (r1.X < (r2.X + r2.Width)) && 
        (r2.Y < r1.Y + r1.Height) &&
        (r1.Y < r2.Y + r2.Height); 
}

这两种方法是等价的——你混合了||和&&

public static bool AreIntersected(Rectangle r1, Rectangle r2)
{
    bool test1 = ((r1.Left > r2.Left + r2.Width) || (r1.Left + r1.Width < r2.Left) || (r1.Top < r2.Top - r2.Height)|| (r1.Top - r1.Height > r2.Top));
    bool test2 = (!(r1.Left > r2.Left + r2.Width) && !(r1.Left + r1.Width < r2.Left) && !(r1.Top < r2.Top - r2.Height) && !(r1.Top - r1.Height > r2.Top));
    return test1; // or test2 as they are logically equivalent
}