constrain method

Rect? constrain(
  1. Rect withinBounds
)

Returns a new Rect if the current Rect is outside the withinBounds otherwise returns null. If the Rect is outside the withinBounds it will be adjusted to fit within the withinBounds maintaining the aspect ratio.

Implementation

Rect? constrain(Rect withinBounds) {
  double aspectRatio = withinBounds.width / withinBounds.height;

  double width = this.width;
  double height = this.height;
  double left = this.left;
  double top = this.top;
  bool needsAdjustment = false;

  if (width > withinBounds.width) {
    width = withinBounds.width;
    height = width / aspectRatio;
    needsAdjustment = true;
  } else if (height > withinBounds.height) {
    height = withinBounds.height;
    width = height * aspectRatio;
    needsAdjustment = true;
  }

  if (left < withinBounds.left) {
    left = withinBounds.left;
    needsAdjustment = true;
  } else if (top < withinBounds.top) {
    top = withinBounds.top;
    needsAdjustment = true;
  } else if (left + width > withinBounds.right) {
    left = withinBounds.right - width;
    needsAdjustment = true;
  } else if (top + height > withinBounds.bottom) {
    top = withinBounds.bottom - height;
    needsAdjustment = true;
  }

  return needsAdjustment ? Rect.fromLTWH(left, top, width, height) : null;
}