【问题标题】:How to proportionally (respecting aspect ratio) scale a rectangle?如何按比例(尊重纵横比)缩放矩形?
【发布时间】:2011-08-26 18:43:17
【问题描述】:

我正在尝试通过设置x 并找到y 来简单地将给定的x 框通过y 并将其放大,反之亦然。这个公式将如何用 Python 表示(为了便于阅读)。我试图把这个盒子装在一个更大的盒子里,这样内盒总是能装在更大的盒子里。

【问题讨论】:

  • 新矩形是否应该在较大的盒子内居中? (即信箱?)
  • 我可以通过数学计算使新矩形居中,这并不难。我总是对实际调整大小的数学感到困惑。

标签: python math aspect-ratio


【解决方案1】:

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

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

【讨论】:

  • 正是我所需要的,没有绒毛
【解决方案2】:
>>> 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)
>>> 

【讨论】:

    【解决方案3】:

    注意:我并不真正使用 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
    

    【讨论】:

      猜你喜欢
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-04
      • 1970-01-01
      相关资源
      最近更新 更多