letterBoxToSquare function

Image letterBoxToSquare(
  1. Image image,
  2. Color backgroundColor
)

Pads a non-square image onto a square canvas of side max(w, h) filled with backgroundColor and centers the source on it. Returns image unchanged when it is already square (idempotent — safe to call multiple times, e.g. by both a platform writer that pre-pads and a downstream createResizedImage call that also has a background color).

Used by platform writers that have a configured background color so a non-square source's aspect ratio is preserved across every generated icon size (upstream #214). Letter-box the source ONCE per platform, then hand the square result to the resize loop.

Implementation

Image letterBoxToSquare(Image image, Color backgroundColor) {
  if (image.width == image.height) {
    return image;
  }
  final size = image.width > image.height ? image.width : image.height;
  final canvas = Image(width: size, height: size, numChannels: 4);
  for (final px in canvas) {
    px.setRgba(
      backgroundColor.r.toInt(),
      backgroundColor.g.toInt(),
      backgroundColor.b.toInt(),
      backgroundColor.a.toInt(),
    );
  }
  final offsetX = (size - image.width) ~/ 2;
  final offsetY = (size - image.height) ~/ 2;
  return compositeImage(canvas, image, dstX: offsetX, dstY: offsetY);
}