如何按比例(尊重长宽比)缩放矩形?

发布于 2024-11-07 18:45:27 字数 162 浏览 0 评论 0原文

我试图简单地获取给定的 xy 框并将其放大,方法是设置 x 并查找 y,反之亦然。这个公式如何用 Python 表达(为了可读性)。我试图将这个盒子放入一个较大的盒子内,以便内盒始终适合较大的盒子。

I'm trying to simply take a given box of x by y and scale it up, either by setting x and finding y, or vice versa. How would this formula be expressed in Python (for readability's sake). I'm trying to fit this box inside of a larger box so that the inner box always fits within the larger box.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

还在原地等你 2024-11-14 18:45:27

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

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

What you need is the relative aspect ratios of the two boxes, since that determines which of the new axes must 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
要走就滚别墨迹 2024-11-14 18:45:27

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

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

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

or

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

淡墨 2024-11-14 18:45:27
>>> 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)
>>> 
>>> 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)
>>> 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文