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


  • dimensions of parent rectangle
  • dimensions of child rectangle


-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

  • $\begingroup$ 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. $\endgroup$
    – platty
    Dec 13 '18 at 19:09
  • $\begingroup$ @platty Child needs to be scaled to preserve its proportions. Dimensions of both input elements are given $\endgroup$
    – AnKing
    Dec 13 '18 at 19:11
  • $\begingroup$ 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? $\endgroup$
    – platty
    Dec 13 '18 at 19:14
  • $\begingroup$ @platty Sorry, this means that input ratio (width/height) for both child and parent rectangles can be more or less than 1 $\endgroup$
    – AnKing
    Dec 13 '18 at 19:18
  • $\begingroup$ 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. $\endgroup$
    – KReiser
    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$.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.