# Scaling rectangle and keeping ratio when height and/or width exceed container

I have a 2D box with a Height of 206 and a Width of 202.

Inside of this box is a Rectangle. It fits until the height and/or width exceed the height/width of its container.

How can I scale the Rectangle and get a new height and width so whenever it exceeds the container box it shrinks back to the largest possible size with the same ratio while fitting into the container?

Example: The Rectangle has a height of 200 and a width of 100. I increase the height to 2000 and the width to 1000. I want to shrink it back down to a size that will fit in the box with a height of 206 and width of 202 while keeping the ratio of 2000:1000.

Note: The height might not always greater than the width.

• You might want to look at Doug Dilon's answer here: quora.com/… . You have an added constraint but the same principle is still useful – Boshu Apr 4 at 21:01
• Let's say you have a box of dimension $(w_b, h_b)$ and a rectangle of dimension $(w_p, h_p)$, the scaling factor will be $$\min\left(\frac{w_b}{w_p},\frac{h_b}{h_p}, 1\right)$$ The $1$ here is to ensure when your box is large enough, don't scale the rectangle. – achille hui Apr 4 at 21:25