ある長方形を別の長方形に合わせて、うまく収まるように中央に配置することがよくあります。ホワイトボードに何かを描いて、ロジックが何であるかを写真に撮りますが、暗くなり、ろうそくの明かりでそれを行うのが楽しくなくなります。
とにかくシンプルで分かりやすいです。これは、私が最初から書き直さなければならなかった関数です (今回は 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 の中央に最大化して配置する必要があります。