cropBoundaries method

Rect cropBoundaries(
  1. Rect boundaries, {
  2. double? minAspectRatio,
  3. double? maxAspectRatio,
})

Clamps this (a crop rect) to stay inside boundaries, optionally honoring an aspect-ratio range. When a part of the rect spills past an edge, it's pushed back; if the resulting aspect violates minAspectRatio / maxAspectRatio, it's resized on its center to snap back into the allowed range.

Used by the Cropper tool whenever the user drags the crop rect or the underlying image transforms — keeps the crop rect inside the image's intersected viewport.

Implementation

Rect cropBoundaries(
  Rect boundaries, {
  double? minAspectRatio,
  double? maxAspectRatio,
}) {
  if (top >= boundaries.top &&
      left >= boundaries.left &&
      bottom <= boundaries.bottom &&
      right <= boundaries.right) {
    return this;
  }
  final w = min(width, boundaries.width);
  final h = min(height, boundaries.height);
  final result = Rect.fromLTRB(
    right >= boundaries.right ? boundaries.right - w : max(boundaries.left, left),
    bottom >= boundaries.bottom ? boundaries.bottom - h : max(boundaries.top, top),
    left <= boundaries.left ? boundaries.left + w : min(boundaries.right, right),
    top <= boundaries.top ? boundaries.top + h : min(boundaries.bottom, bottom),
  );
  final ar = result.width / result.height;
  final lock = minAspectRatio != null && ar < minAspectRatio
      ? minAspectRatio
      : maxAspectRatio != null && ar > maxAspectRatio
          ? maxAspectRatio
          : null;
  if (lock != null) {
    return result.resize(
      min(result.width, result.height * lock),
      min(result.height, result.width / lock),
    );
  }
  return result;
}