gpt4 book ai didi

java - 找出矩形是否重叠

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:49:09 25 4
gpt4 key购买 nike

我给每个矩形两个点,左上角和右下角(两个矩形的点表示为 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");

}

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

最佳答案

这是在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com