我经常将一个矩形套进另一个矩形中,以使其完美地居中。
我会在白板上画出一些逻辑,并拍下照片,但现在天色已暗,蜡烛光线不太适合这样做。
无论如何,这很简单易懂。以下是我刚刚再次从头开始编写的函数(这次使用PHP):
无论如何,这很简单易懂。以下是我刚刚再次从头开始编写的函数(这次使用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中。