Fitting the largest rectangle inside another one

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 × War / Har < Wimg / Himg

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(Wimg / War, Himg, Har)

And the dimensions I need are f × War (width) and f × Har (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.

Mathematically, that’s the simplest… though you have to account for the possibility that the original image is already too big for your box, so be careful with your definition of “smallest”.

I tried that too and it actually works as well :slightly_smiling_face:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.