How to scale the rectangle proportionally (taking into account the aspect ratio)?

I'm trying to just take the given block xon yand scale it by setting xand finding y, or vice versa. How would this formula be expressed in Python (for readability). I am trying to install this box inside a larger one so that the inner box always goes into the big box.

+3
source share
3 answers

NB: I really don't do Python, so this is pseudo code.

You need the relative proportions of the two fields, as this determines which of the new axes should be the same size as the new box:

r_old = old_w / old_h
r_new = new_w / new_h

if (r_old > r_new) then
   w = new_w              // width of mapped rect
   h = w / r_old          // height of mapped rect
   x = 0                  // x-coord of mapped rect
   y = (new_h - h) / 2    // y-coord of centered mapped rect
else
   h = new_h
   w = h * r_old
   y = 0
   x = (new_w - w) / 2
endif
+6
source

new_y = (float(new_x) / x) * y

or

new_x = (float(new_y) / y) * x

+6
source
>>> import fractions
>>> x, y = 10, 10
>>> fix_rat = fractions.Fraction(x, y)
>>> fix_rat
Fraction(1, 1)
>>> x = 8
>>> if fractions.Fraction(x, y) != fix_rat:
    y = x / fix_rat #well instead of y you should put the last one that has been changed
                    #but this is just an example


>>> y
Fraction(8, 1)
>>> 
0

All Articles