[英]java.awt.Rectangle#intersects(Rectangle r) ugly implementation?
以下是來自 awt Rectangle源代碼的intersects(Rectangle r)
方法。
我添加了一些與我的問題相關的以//*
開頭的評論:
由於代碼驗證 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 < ry
和tw < tx
和th < ty
。
rw < rx
、 rh < ry
、 tw < tx
和th < 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 ;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.