resizeCropToRatio function

Rect resizeCropToRatio(
  1. Size layout,
  2. Rect crop,
  3. double r
)

Returns a new crop Rect that respect r aspect ratio inside a layout and based on an existing crop area

This rect must not become smaller and smaller, or be out of bounds from layout

Implementation

Rect resizeCropToRatio(Size layout, Rect crop, double r) {
  // if target ratio is smaller than current crop ratio
  if (r < crop.size.aspectRatio) {
    // use longest crop side if smaller than layout longest side
    final double maxSide = min(crop.longestSide, layout.shortestSide);
    // to calculate the ratio of the new crop area
    final Size size = Size(maxSide, maxSide / r);

    final Rect rect = Rect.fromCenter(
      center: crop.center,
      width: size.width,
      height: size.height,
    );

    // if res is smaller than layout we can return it
    if (rect.size <= layout) return translateRectIntoBounds(layout, rect);
  }

  // if there is not enough space crop to the middle of the current [crop]
  final Size newCenteredCrop = computeSizeWithRatio(crop.size, r);
  final Rect rect = Rect.fromCenter(
    center: crop.center,
    width: newCenteredCrop.width,
    height: newCenteredCrop.height,
  );

  // return rect into bounds
  return translateRectIntoBounds(layout, rect);
}