clampToBounds method

CropRegion clampToBounds({
  1. required int sourceWidth,
  2. required int sourceHeight,
})

Returns this region clamped to an image of sourceWidth x sourceHeight.

The returned rectangle is always at least 1 pixel wide and high. Negative or zero input sizes are normalized to a 1px crop anchored near x and y, while out-of-range coordinates are moved inside the image bounds.

Implementation

CropRegion clampToBounds({
  required int sourceWidth,
  required int sourceHeight,
}) {
  if (sourceWidth <= 0) {
    throw ArgumentError.value(
      sourceWidth,
      'sourceWidth',
      'Source width must be greater than zero.',
    );
  }
  if (sourceHeight <= 0) {
    throw ArgumentError.value(
      sourceHeight,
      'sourceHeight',
      'Source height must be greater than zero.',
    );
  }

  final left = x.clamp(0, sourceWidth - 1).toInt();
  final top = y.clamp(0, sourceHeight - 1).toInt();
  final rawRight = hasPositiveSize ? x + width : x + 1;
  final rawBottom = hasPositiveSize ? y + height : y + 1;
  final right = rawRight.clamp(left + 1, sourceWidth).toInt();
  final bottom = rawBottom.clamp(top + 1, sourceHeight).toInt();
  final boundedWidth = right - left;
  final boundedHeight = bottom - top;
  final safeCornerRadius = cornerRadius.isFinite ? cornerRadius : 0.0;
  final maxCornerRadius = math.min(boundedWidth, boundedHeight) / 2;

  return CropRegion(
    x: left,
    y: top,
    width: boundedWidth,
    height: boundedHeight,
    cornerRadius: safeCornerRadius.clamp(0, maxCornerRadius).toDouble(),
  );
}