java - 判断矩形是否重叠

标签 java algorithm geometry overlap rectangles

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

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

            }

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

最佳答案

这是在 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.
    }

关于java - 判断矩形是否重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33071855/

相关文章:

java - Spring bean 配置

algorithm - 提高序数排名

algorithm - 如何检测平行线段的顺序?

c# - 在二次贝塞尔曲线路径上寻找点

python - 如何使用 sympy 从 View 矩阵中提取眼睛/目标/向上?

java - JPA查询: java. lang.ClassCastException : [Enum] cannot be cast to java. lang.Enum

java - TCPTransportConnection 内存泄漏

java - java中如何获取被调用方法的名称

algorithm - 有没有办法优化此代码以查找数字的除数?

arrays - 使用循环打印值