[Math] How to keep aspect ratio and position of rectangle inside another rectangle

algebra-precalculusratiorectangles

This problem has plagued me for many years.

Given two rectangles how do I resize the first to fit into the second while preserving the aspect ratio? The second rectangle could be bigger or smaller than the first.

Here are the variables I have to work with where the first rectangle is represented as an image:

// these variables contain the image and container sizes
imageWidth
imageHeight
targetWidth
targetHeight
adjustedImageWidth
adjustedImageHeight

imageAspectRatio = imageWidth/imageHeight;
targetAspectRatio = targetWidth/targetHeight;

What I have found so far as the next step (from open source code):

if (imageAspectRatio > targetAspectRatio) {
    adjustedHeight = targetWidth / imageAspectRatio;
else
    adjustedWidth = targetHeight * imageAspectRatio;
}

// define size and position of image
// to fit inside second rectangle

I do not know what to do next.

Best Answer

I do not understand what you mean by keeping the position the same, so I will just find the largest scaling of rectangle 1 that fits into rectangle 2. Basically you just find the scaling that works for the width and the scaling that works for the height and take the minimum. If the first rectangle is $h_1 \times w_1$ and the second is $h_2 \times w_2$ you write

vert scale $=\frac {h_2}{h_1}$
horiz scale $= \frac {w_2}{w_1}$
$\text{scale}=\min($horiz scale, vert scale)
new dimensions $=\text{scale} \cdot h_1 \times \text{scale} \cdot w_1$
The new dimensions will fit within the second rectangle, touching on two sides.

If you want to keep the center point (say) of rectangle $1$ and find the largest scaling possible, you do the same as above, but compute four scaling factors, one for each side, then take the minimum. It will touch on one side only.