找出矩形是否重叠

时间:2015-10-12 01:10:51

标签: java algorithm geometry overlap rectangles

我给每个矩形两个点,左上角和右下角(两个矩形的点表示为bR1和bR2,左上角的点表示为tL1和tL2,等等),我想知道两个矩形是否重叠。现在我的代码如下:

            if(!(bR1.y < tL2.y || 
                tL1.y > bR2.y || 
                bR1.x < tL2.x || 
                tL1.x > bR2.x ) )
                //if this combination of conditions are met, then the rectangles overlap at some point
                //
            {
                System.out.println("overlap found");

            }

            else if (rectangle1.tL.equals(rectangle2.tL) &&
                    rectangle1.bR.equals(rectangle2.bR))
            //if this combination of conditions are met, then the rectangles are perfectly on top of one another
            {
                System.out.println("rectangles completely overlap");

            }

            else if(bL1.x>bL2.x &&
                    bL1.y<bL2.y &&
                    tR1.x<tR2.x &&
                    tR1.y>tR2.y) //if rectangle1 is within rectangle2
            {
                System.out.println("one rectangle completely within another");

            }

            else if(bL1.x<bL2.x &&
                    bL1.y>bL2.y &&
                    tR1.x>tR2.x &&
                    tR1.y<tR2.y)//if rectangle2 is within rectangle1
            {
                System.out.println("one rectangle completely within another");

            }

根据我的测试,我的算法发现重叠太少。我几乎可以肯定,我的算法唯一的问题是它没有考虑正方形,只有边缘或角落正在接触。是这样的吗?如果是,那么我该如何解决只有边缘重叠的问题? (我可以轻松地解决角落触摸问题,就像我解决矩形完美贴合在彼此之上一样。)

1 个答案:

答案 0 :(得分:2)

以下是在Rectangle2D的java AWT源代码中解决的问题:http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/awt/geom/Rectangle2D.java#675

一般来说,你可以使用类似的东西:

    if (Math.max(tL1.x, tL2.x) <= Math.min(bR1.x, bR2.x) &&
            Math.max(tL1.y, tL2.y) <= Math.min(bR1.y, bR2.y)) {
        // It covers all cases of intersection including equality and inclusion.
    }