重叠的矩形

时间:2016-09-15 20:26:02

标签: c# math geometry rectangles

每个人都过得愉快!所以,我有一个像this one这样的案例。 我需要编写一个方法,说明矩形是否相互重叠。输入如下:高度,宽度,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));
    }    

Screen of the error

And here it works just fine

非常感谢你的帮助!

3 个答案:

答案 0 :(得分:3)

答案在您关联的页面上。对代码的唯一更改是将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 Rectangle struct,则该对象内置了RightBottom属性,因此无需替换代码。

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

当然,您也可以轻松使用静态Rectangle.Intersect方法。

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

答案 1 :(得分:2)

使用Rectangle.Intersect

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); 
}

答案 2 :(得分:1)

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

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
}           
相关问题