java.awt.Rectangle#intersects(Rectangle r) 丑化实现?

问题描述 投票:0回答:1

以下是 intersects(Rectangle r) 方法从awt 矩形 源代码。我添加了一些以 //* 与我的问题有关。既然代码验证了rw(例如)是正数 那么rw rw+rx 要大于 rx. 如果是这样的话 rw < rx 总是假的,为什么要检查?

/**
 * Determines whether or not this {@code Rectangle} and the specified
 * {@code Rectangle} intersect. Two rectangles intersect if
 * their intersection is nonempty.
 *
 * @param r the specified {@code Rectangle}
 * @return    {@code true} if the specified {@code Rectangle}
 *            and this {@code Rectangle} intersect;
 *            {@code false} otherwise.
 */
public boolean intersects(Rectangle r) {
    int tw = width;
    int th = height;
    int rw = r.width;
    int rh = r.height;
    if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) return false;
    int tx = x;
    int ty = y;
    int rx = r.x;
    int ry = r.y;
    //*at this point rw must be positive
    rw += rx;    //*after this assignment rw must be bigger than rx
    rh += ry;
    tw += tx;
    th += ty;
    //      overflow || intersect
    return (rw < rx || rw > tx) &&  //*rw < rx should always be false
            (rh < ry || rh > ty) &&
            (tw < tx || tw > rx) &&
            (th < ty || th > ry);
}

这同样适用于 rh < rytw < txth < ty.

java swing awt
1个回答
0
投票

测试 rw < rx , rh < ry, tw < txth < ty 是多余的,可以去掉。

public boolean intersects(Rectangle r) {

    int tw = width;
    int th = height;
    int rw = r.width;
    int rh = r.height;
    if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0)return false;

    rw += r.x;
    rh += r.y;
    tw += x;
    th += y;

    return  rw > x &&
            rh > y &&
            tw > r.x &&
            th > r.y;
}

在这样做之后,我们可以更进一步, 使代码更加可读和简洁。

public boolean intersects(Rectangle other) {

      //to intersect both vertical and horizontal edges need to cross
      return
                //check if horizontal edge cross
                other.width + other.x > x &&   //other max x is bigger than min x and
                other.x < width + x   &&       //other min x is smaller than max x
                //check if vertical edge cross
                other.height+ other.y > y &&
                other.y <height + y ;
}
© www.soinside.com 2019 - 2024. All rights reserved.