/** * Calculates the smallest rectangle that encompasses both rectangles. The returned rectangle will * have its y-axis in the same orientation as this rectangle * * @param other the other rectangle to compute the bounds with * @return the bounding rectangle */ public Rectangle bounds(Rectangle other) { // get x/x2 values int x = Math.min(this.x, other.x); int x2 = Math.max(this.x2, other.x2); // get y/y2 values final int y = Math.min(other.y, this.y); final int y2 = Math.max(other.y2, this.y2); return Rectangle.fromBounds(x, y, x2, y2); }
/** * Moves all edges closer to the center by an amount. * * @param amount the amount to move the edges in by * @return the shrunk rectangle. Negative amounts will expand the rectangle. * @throws IllegalArgumentException if the rectangle is shrunk pass 0 width/height */ public Rectangle shrunk(int amount) { int x = this.x + amount; int x2 = this.x2 - amount; int y = this.y + amount; int y2 = this.y2 - amount; try { return Rectangle.fromBounds(x, y, x2, y2); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Rectangle shrunk too much!", e); } }
/** * Calculates the intersection of the two rectangles. If no intersection is found, then null is * returned. The returned rectangle will have its y-axis system in the same system as this * rectangle. * * @param other the other rectangle to compute the intersection with * @return the intersected rectangle. null if there as no intersection. * @throws NullPointerException if the other rectangle is null */ public Rectangle intersection(Rectangle other) { // get x/x2 values final int x = Math.max(this.x, other.x); final int x2 = Math.min(this.x2, other.x2); if (x > x2) return null; // get y/y2 values final int y = Math.max(other.y, this.y); final int y2 = Math.min(other.y2, this.y2); if (y > y2) return null; return Rectangle.fromBounds(x, y, x2, y2); }