coverFitScaleOffset function
Cover-fit scale + offset for rendering a source region of size
(sourceW, sourceH) into a viewport of size (viewW, viewH).
Preserves aspect ratio and centers; the source is scaled to cover the
viewport (by the larger of the width/height ratios), so the axis that
overflows is centered with a zero or negative offset and the other axis
offset is zero. The record (scale, offsetX, offsetY) is what a
CustomPainter typically needs to transform source coordinates to
viewport coordinates: x_view = x_source * scale + offsetX.
Implementation
({double scale, double offsetX, double offsetY}) coverFitScaleOffset(
int sourceW,
int sourceH,
double viewW,
double viewH,
) {
final double sourceAspect = sourceW / sourceH;
final double viewAspect = viewW / viewH;
if (sourceAspect > viewAspect) {
final double s = viewH / sourceH;
return (scale: s, offsetX: (viewW - sourceW * s) / 2, offsetY: 0.0);
}
final double s = viewW / sourceW;
return (scale: s, offsetX: 0.0, offsetY: (viewH - sourceH * s) / 2);
}