Mh Mh Mh.. bella O_oOriginariamente inviato da filippo.toso
Mah, non vedo il motivo di utilizzare dei cicli per eseguire delle semplici operazioni matematiche:
Codice PHP:
<?php
function constrain(&$width, &$height, $maxwidth = false, $maxheight = false, $round = true) {
$maxwidth = $maxwidth === false ? $width : $maxwidth;
$maxheight = $maxheight === false ? $height : $maxheight;
$wscale = $width / $maxwidth;
$hscale = $height / $maxheight;
if ($wscale > $hscale) {
$height = $height * $maxwidth / $width;
$width = $maxwidth;
} else {
$width = $width * $maxheight / $height;
$height = $maxheight;
}
$width = $round ? round($width) : $width;
$height = $round ? round($height) : $height;
}
function offset($width, $height, $maxwidth, $maxheight) {
$left = round(($maxwidth - $width) / 2);
$right = $maxwidth - $width - $left;
$top = round(($maxheight - $height) / 2);
$bottom = $maxheight - $height - $top;
return array('left' => $left, 'right' => $right,
'top' => $top, 'bottom' => $bottom);
}
$width = 300;
$height = 200;
$maxwidth = 100;
$maxheight = 100;
constrain($width, $height, $maxwidth, $maxheight);
print($width . ' ' . $height);
$offset = offset($width, $height, $maxwidth, $maxheight);
print('<pre>');
print_r($offset);
print('</pre>');
?>