提示信息

php, 等比列缩小一个矩形, 长和宽分别不能超过某个值。

海浪 已关注

在 PHP 中,你可以通过以下方式实现矩形的等比例缩小,同时保证长和宽不超过某个值:

  1. <?php
  2. function scaleRectangle($width, $height, $maxWidth, $maxHeight) {
  3. // 计算缩放比例
  4. $scale = min($maxWidth / $width, $maxHeight / $height);
  5. // 如果缩放比例大于1,说明原始矩形的长和宽都小于最大值,无需缩放
  6. if ($scale >= 1) {
  7. return [$width, $height];
  8. }
  9. // 以计算出的缩放比例对原始矩形进行等比例缩小
  10. return [$width * $scale, $height * $scale];
  11. }
  12. // 原始矩形的长和宽
  13. $width = 800;
  14. $height = 600;
  15. // 最大长和宽
  16. $maxWidth = 500;
  17. $maxHeight = 400;
  18. list($scaledWidth, $scaledHeight) = scaleRectangle($width, $height, $maxWidth, $maxHeight);
  19. echo "Scaled width: $scaledWidth, Scaled height: $scaledHeight"; // 输出 "Scaled width: 500, Scaled height: 375"
  20. ?>

这段代码首先计算了将矩形缩小到最大长或最大宽所需要的缩放比例。如果缩放比例大于1,表示原始矩形的长和宽都小于最大值,无需缩放。否则,按照计算出的缩放比例对原始矩形进行等比例缩小。

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
海浪 关注 已关注

最近一次登录:2024-01-08 08:31:52   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图