php, 等比列缩小一个矩形, 长和宽分别不能超过某个值。
在 PHP 中,你可以通过以下方式实现矩形的等比例缩小,同时保证长和宽不超过某个值:
<?php
function scaleRectangle($width, $height, $maxWidth, $maxHeight) {
// 计算缩放比例
$scale = min($maxWidth / $width, $maxHeight / $height);
// 如果缩放比例大于1,说明原始矩形的长和宽都小于最大值,无需缩放
if ($scale >= 1) {
return [$width, $height];
}
// 以计算出的缩放比例对原始矩形进行等比例缩小
return [$width * $scale, $height * $scale];
}
// 原始矩形的长和宽
$width = 800;
$height = 600;
// 最大长和宽
$maxWidth = 500;
$maxHeight = 400;
list($scaledWidth, $scaledHeight) = scaleRectangle($width, $height, $maxWidth, $maxHeight);
echo "Scaled width: $scaledWidth, Scaled height: $scaledHeight"; // 输出 "Scaled width: 500, Scaled height: 375"
?>
这段代码首先计算了将矩形缩小到最大长或最大宽所需要的缩放比例。如果缩放比例大于1,表示原始矩形的长和宽都小于最大值,无需缩放。否则,按照计算出的缩放比例对原始矩形进行等比例缩小。