如何按比例(尊重纵横比)缩放矩形?

Naf*_*Kay 3 python math aspect-ratio

我想简单地给定的盒子xy放大以达到,通过设置x和发现y,反之亦然.如何用Python表达这个公式(为了便于阅读).我试图将这个盒子放在一个更大的盒子里面,这样内盒子总能放在更大的盒子里面.

blu*_*ume 6

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

要么

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


Aln*_*tak 6

注意:我不是真的做Python,所以这是伪代码.

您需要的是两个框的相对宽高比,因为它确定哪个新轴必须与新框的大小相同:

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
Run Code Online (Sandbox Code Playgroud)