在Java中检测矩形邻接

时间:2013-12-08 02:16:23

标签: java algorithm geometry shapes

我已使用正确的Rectangleintersects(Rectangle)方法实施了以下contains(Rectangle) POJO:

public class Rectangle {
    private double x;       // x-value of upper-left corner of rectangle
    private double y;       // y-value of upper-left corner of rectangle
    private double width;   // width of the rectangle
    private double height;  // height of the rectangle

    // Returns true if this Rectangle intersects otherRectangle.
    public boolean intersects(Rectangle otherRectangle) {
        double x = otherRectangle.getX();
        double y = otherRectangle.getY();
        double w = otherRectangle.getWidth();
        double h = otherRectangle.getHeight();
        double x0 = getX();
        double y0 = getY();

        if(isEmpty() || w <= 0 || h <= 0)
            return false;

        return (
            x + w > x0 &&
            y + h > y0 &&
            x < x0 + getWidth() &&
            y < y0 + getHeight()
        );
    }

    // Returns true if this Rectangle contains otherRectangle.
    public boolean contains(Rectangle otherRectangle) {
        double x = otherRectangle.getX();
        double y = otherRectangle.getY();
        double w = otherRectangle.getWidth();
        double h = otherRectangle.getHeight();
        double x0 = getX();
        double y0 = getY();

        return (
            x >= x0 &&
            y >= y0 &&
            x < x0 + getWidth() &&
            y < y0 + getHeight()
        );
    }

    // Returns true if this Rectangle is adjacent to otherRectangle.
    public boolean isAdjacentTo(Rectangle otherRectangle) {
        // ???
    }
}

现在我正在尝试实施isAdjacentTo并且正在窒息。另一个SOer告诉我,为了邻接,我可以:

  

...只需对一个轴(如顶部和底部)进行遏制检查,然后确保每个角不包含在另一个方向上(如水平方向)。

但我还是没有想象出解决方案。有任何想法吗?最好我可以使用intersectscontains方法,但我会采取任何真正有效的方法。

1 个答案:

答案 0 :(得分:2)

确定。我将分别编制一些方法leftSide()rightSide()topSide()bottomSide(),它们分别是矩形的左,右,顶部和底部(底部是在数值上小于顶部,但如果它显示在屏幕上它将是顶部)。

然后是代码:

// Returns true if this Rectangle is adjacent to otherRectangle.
public boolean isAdjacentTo(Rectangle otherRectangle, double tolerance) {
    if(Math.abs(getLeftSide()-otherRectangle.getRightSide())<tolerance||Math.abs(otherRectangle.getLeftSide()-getRightSide())<tolerance)
    {
        return !(getTopSide()<otherRectangle.getBottomSide()||otherRectangle.getTopSide()<getBottomSide());
    }
    if(Math.abs(getTopSide()-otherRectangle.getBottomSide())<tolerance||Math.abs(otherRectangle.getTopSide()-getBottomSide())<tolerance)
    {
        return !(getRightSide()<otherRectangle.getLeftSide()||otherRectangle.getRightSide()<getLeftSide());
    }
    return false;
}

现在这就是它的作用。 一个的顶侧是否与另一侧的底侧相同? 是的 - &gt;如果它们之间没有空格,则返回true。 (我正在检查一个的右侧是否在另一侧的左侧(对于两个矩形)) 不 - &gt;做同样的事情分享左/右方

如果他们不分享右/左方返回虚假,因为他们不分享任何一方。

使用容差是因为您无法比较双精度是否相等。