This week I needed a way to figure out how to get the largest rectangle with a predefined aspect ratio that fits into another rectangle. So let’s say I have an image of arbitrary size and I want it cropped to something with a 16:9 aspect ratio and as big as could possibly fit.

I figured the formula to solve is basically

f × W_{ar} / H_{ar} < W_{img} / H_{img}

Where W and H are width and height respectively of the aspect ratio (ar) and the image (img)

So then I’d need to find the largest value of f for which this still holds.

This can be obtained by figuring out the scale for width and the scale for height and taking the smallest one, i. e.,

f = min(W_{img} / W_{ar}, H_{img}, H_{ar})

And the dimensions I need are f × W_{ar} (width) and f × H_{ar} (height)

This works a charm, but I’m wondering if this is the most optimal way of doing things or if there is another way I’ve missed.