检查矩形B是否完全包含在矩形A中

本文关键字:包含 是否 检查 | 更新日期: 2023-09-27 18:21:52

大家好,帮我检查矩形B是否完全包含在矩形A中,这里有一个要使用的示例代码:

类矩形

Public class Rectangle
{
    Public int X1 { get; set; }
    Public int X2 { get; set; }
    Public int Y1 { get; set; }
    Public int Y2 { get; set; }
    public bool IsWhollyContained(Rectangle otherRectangle)
    {
        //Write your code here
    }
}

主要方法

Public static void main(string[] args)
{
    Rectangle A = new Rectangle { X1 = 2, Y1 = 1, X2 = 4, Y2 = 4}};
    Rectangle B = new Rectangle { X1 = 1, Y1 = 6, X2 = 5, Y2 = 1}};
    bool isContained = B.IsWhollyContained(A);
}

任务是完成方法IsWhollyContained。如果你知道答案,请提供帮助,使用的语言是C#。谢谢大家。

检查矩形B是否完全包含在矩形A中

对矩形的点进行排序,以确保获得矩形的右边界,而不是比较点,请尝试以下操作:

public bool IsWhollyContained(Rectangle otherRectangle)
{
    int rec1Xb = X1 > X2 ? X1 : X2;
    int rec1Xs = X1 > X2 ? X2 : X1;
    int rec1Yb = Y1 > Y2 ? Y1 : Y2;
    int rec1Ys = Y1 > Y2 ? Y2 : Y1;

    int rec2Xb = otherRectangle.X1 < otherRectangle.X2 ? otherRectangle.X1 : otherRectangle.X2;
    int rec2Xs = otherRectangle.X1 < otherRectangle.X2 ? otherRectangle.X2 : otherRectangle.X1;
    int rec2Yb = otherRectangle.Y1 < otherRectangle.Y2 ? otherRectangle.Y1 : otherRectangle.Y2;
    int rec2Ys = otherRectangle.Y1 < otherRectangle.Y2 ? otherRectangle.Y2 : otherRectangle.Y1;
    return  rec1Xs >= rec2Xs &&
            rec1Xb <= rec2Xb &&
            rec1Ys >= rec2Ys &&
            rec1Yb <= rec2Yb;
}

我假设X1、X2、Y1和Y2是矩形左下角和右上角的坐标
如果假设另一个矩形位于第一个矩形内部,则必须满足以下条件:

rectangle1.X1 < rectangle2.X1
rectangle1.Y1 < rectangle2.Y1
rectangle1.X2 > rectangle2.X2
rectangle1.Y2 > rectangle2.Y2

但是,您不需要将所有这些坐标存储在矩形中。System。Drawing有一种叫做Point的东西,你可以为它指定X坐标和Y坐标。但如果你已经包括了System。Drawing,你可以按照Hazem Abdullah的建议去做。

如果使用System.Drawing Rectangle ,则可以使用以下代码

Rectangle rect1, rect2;
// initialize them
if(rect1.Contains(rect2))
{
    // do...
}

这是链接1

如果你使用自己的矩形,你可以检查第一个矩形的所有角点是否属于第二个。

bool PointInsideRectangle(Point pt, double y0, double x0, double y1, double x1)
{
   if (x1 < x0)
    {
        return pt.X < x0 && pt.X > x1 && pt.Y < y0 && pt.Y > y1;
    }
    // it crosses the date line
    return (pt.X < x0 || pt.X > x1) && pt.Y < y0 && pt.Y > y1;        
}

或者,您只需要检查第一个矩形的x0,y0,就可以与第二个矩形的x0,yO进行比较,以及与第一个矩形之间的高度进行比较。