# Algorithm to draw an image within arbitrary size rectangle

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

• What proportions are you trying to preserve? It's not clear what it means for the width and height to be randomly generated if you're given the dimensions. Dec 13 '18 at 19:09
• @platty Child needs to be scaled to preserve its proportions. Dimensions of both input elements are given Dec 13 '18 at 19:11
• What do you mean by "Parent/Child can be horizontal or vertical" if you're not allowing rotations. Does this just mean that the length and width are given along the axes and rotations are not allowed? Dec 13 '18 at 19:14
• @platty Sorry, this means that input ratio (width/height) for both child and parent rectangles can be more or less than 1 Dec 13 '18 at 19:18
• Please read the tag descriptions before you select them - "algebraic-geometry" was in no way related to your question. Choosing appropriate tags helps you receive good answers. Dec 13 '18 at 20:57

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$$.