Algorithm to draw an image within arbitrary size rectangle

geometry

I'm writing an application that needs to draw an arbitrary size image (width and height are random at the input) within another randomly generated rectangle(dimensions given as input) so that the inside image is scaled proportionally and not distorted(but fits within).

Given:

  • dimensions of parent rectangle
  • dimensions of child rectangle

Cond:

-Child rectangle should always be as big as possible within parent(needs scaled preserving proportions)

-Parent can be horizontal or vertical.

-Child can be horizontal or vertical.

-Parent/child should not be rotated (top stays on top)

What is needed:

-dimensions of resulted child rectangle

enter image description here

Best Answer

Let $w_P, h_P$ be the parent dimensions and $w_C, h_C$ be the child dimensions. You want to scale the child rectangle so that both dimensions are at most those of the parent. In other words, you want to find the largest $k$ such that $k \cdot w_C \leq w_P$ and $k \cdot h_C \leq h_P$ both hold. But these just give the inequalities: $$ \begin{align*} k &\leq \frac{w_P}{w_C} \\ k &\leq \frac{h_P}{h_C} \end{align*} $$ If both of these must be satisfied, then the largest $k$ can be is $\min \left\{ \frac{w_P}{w_C}, \frac{h_P}{h_C} \right\}$. Then the dimensions of the scaled rectangle are $k \cdot w_C$ and $k \cdot h_C$.