MathUtils.findPreferredRatio
Ever had the problem to shrink a picture so that it fits into a Box that has a specific width and height?
Here is a really nice and very useful method that helps finding the needed ratio:
/** * The <code>findPreferredRatio</code> method is used to find the correct ratio to fit content in a container using a maximum area. * * @param $width Number * @param $height Number * @param $maxWidth Number * @param $maxHeight Number * @return * */ public static function findPreferredRatio($width:Number, $height:Number, $maxWidth:Number, $maxHeight:Number):Number { var dw:Number = $maxWidth/$width; var dh:Number = $maxHeight/$height; return dw < dh ? dw : dh; }
Example:
var pic:Bitmap = new Bitmap(new BitmapData(1000, 1000, false, 0)); var ratio:Number = MathUtils.findPreferredRatio(pic.width, pic.height, 280, 180); pic.width *= ratio; pic.height *= ratio; trace(pic.width+'x'+pic.height); //output: 180x180
Tags: actionscript, codesnippet, dev, flash
Brilliant. Just what I needed, thanks!