Rectangle (final Rectangle source, final Rectangle toCrop) { final Rectangle result = new Rectangle(toCrop); if (toCrop.x < source.x) { result.width -= source.x - toCrop.x; result.x = source.x; } if (toCrop.y < source.y) { result.height -= source.y - toCrop.y; result.y = source.y; } if (result.x + result.width > source.x + source.width) { result.width = source.x + source.width - result.x; } if (result.y + result.height > source.y + source.height) { result.height = source.y + source.height - result.y; } return result; }