computeLetterboxParams function

LetterboxParams computeLetterboxParams({
  1. required int srcWidth,
  2. required int srcHeight,
  3. required int targetWidth,
  4. required int targetHeight,
  5. bool roundDimensions = true,
})

Computes letterbox parameters for resizing srcWidthxsrcHeight to fit within targetWidthxtargetHeight while preserving aspect ratio.

The scale factor is min(targetWidth/srcWidth, targetHeight/srcHeight). The image is resized to newWidthxnewHeight and then padded symmetrically to exactly targetWidthxtargetHeight. Any remainder pixel goes to the right/bottom pad.

Set roundDimensions to false to truncate (.toInt()) instead of rounding the scaled dimensions. Defaults to true (.round()).

Implementation

LetterboxParams computeLetterboxParams({
  required int srcWidth,
  required int srcHeight,
  required int targetWidth,
  required int targetHeight,
  bool roundDimensions = true,
}) {
  final double scale = math.min(
    targetWidth / srcWidth,
    targetHeight / srcHeight,
  );
  final int newWidth = roundDimensions
      ? (srcWidth * scale).round()
      : (srcWidth * scale).toInt();
  final int newHeight = roundDimensions
      ? (srcHeight * scale).round()
      : (srcHeight * scale).toInt();
  final (padLeft, padRight) = _centeredPad(targetWidth, newWidth);
  final (padTop, padBottom) = _centeredPad(targetHeight, newHeight);

  return LetterboxParams(
    scale: scale,
    newWidth: newWidth,
    newHeight: newHeight,
    padLeft: padLeft,
    padTop: padTop,
    padRight: padRight,
    padBottom: padBottom,
  );
}