gpt4 book ai didi

algorithm - 将一个矩形装入另一个矩形

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:44:32 24 4
gpt4 key购买 nike

我经常将一个矩形放入另一个矩形中,这样它就可以很好地对齐并居中。我会在白板上画一些东西并拍下逻辑是什么,但是天色越来越暗,烛光使它变得不那么有趣了。

总之,它非常简单易懂。这是我不得不再次从头开始编写的函数(这次是在 PHP 中):

// Fit rectangle 2 into rectangle 1 to get rectangle 3
// Rectangle 3 must be centered
// Return dimensions of rectangle and position relative to rectangle 1

function fitrect($w1,$h1,$w2,$h2){

// Let's take a chance with rectangle 3 width being equal to rectangle 1 width
$w3=$w1;
$h3=$w3*($h2/$w2);

// Check if height breaks rectangle 1 height
if($h3>$h1){
// Recalculate dimensions and then position
$h3=$h1;
$w3=$h3*($w2/$h2);
$x3=($w1-$w3)/2;
$y3=0;
}else{
// Just calculate position
$y3=($h1-$h3)/2;
$x3=0;
}

// Tidy up
$x3=round($x3);
$y3=round($y3);
$w3=round($w3);
$h3=round($h3);

// Result array
$res=array($x3,$y3,$w3,$h3);

return($res);

}

我想了解这个算法和它的其他版本,这样我的大脑就能理解这些基础知识,这样我就不必再依赖笔和纸(或白板)了。

那么,你会怎么做呢?什么绒毛可以去除?

编辑:举个例子 - 假设我们的矩形 1 的尺寸为 256x256,矩形 2 的尺寸为 44x167。然后我们需要将矩形 2 缩放到 67x256 并将其定位在相对于矩形 1 的 94,0 处,以便它最大化并集中在矩形 1 中。

最佳答案

这是我的做法。

让我们定义一个术语,fatness,它等于矩形的宽度与高度的比率。高度为 1、宽度为 10 的矩形的肥胖度为 10。高度为 20、宽度为 10 的矩形的肥胖度为 0.5。当您调整矩形大小时,它的粗度不会改变。

当您放大或缩小矩形 2 的大小以使其宽度等于矩形 1 时,只要矩形 2 比矩形 1 宽,它就不会溢出顶部或底部。它如果 1 比 2 大,溢出。现在您可以提前知道是调整大小以获得合适的宽度还是合适的高度。此外,两种情况的转换逻辑相同,因此可以超出 if/else block 。

伪代码:(抱歉,我不懂 PHP)

fatness1 = w1 / h1
fatness2 = w2 / h2

#adjust scaling
if fatness2 >= fatness1:
#scale for a snug width
scaleRatio = w1 / w2
else:
#scale for a snug height
scaleRatio = h1 / h2
w3 = w2 * scaleRatio
h3 = h2 * scaleRatio


#adjust rectangle 3's center so it is the same as 1's center
xCenterOf1 = x1 + (w1 / 2)
yCenterOf1 = y1 + (h1 / 2)

x3 = xCenterOf1 - (w3 / 2)
y3 = yCenterOf1 - (h3 / 2)

return (x3, y3, w3, h3)

在 python 中测试,假设矩形 1 位于 (0,0),scale(256,256, 44, 167) 返回 (0.0, 94.3, 256.0, 67.4) .

关于algorithm - 将一个矩形装入另一个矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13384594/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com