Resizing with RatioUtil

Written by Aaron Clinger on January 28th, 2009

With the increasing frequency of full browser and full screen Flash sites, many require dynamic content scaling. RatioUtil makes it easy to scale items while maintaining their aspect ratio.

Assuming the Mona Lisa bitmap is 175x150 at its native size and the target bounding box (bounds) is 143x143, here is how scaleToFit would work:

var monaLisaSize:Rectangle = new Rectangle(0, 0, 175, 150); // The Rectangle's x and y values are ignored.
var bounds:Rectangle       = new Rectangle(0, 0, 143, 143); // The Rectangle's x and y values are ignored.

var result:Rectangle  = RatioUtil.scaleToFit(monaLisaSize, bounds);
monaLisaBitmap.width  = result.width;
monaLisaBitmap.height = result.height;

Which would look something like this:

If the image needs to completely fill the bounds you would use the scaleToFill method. The code is exactly the same as above, besides the method substitution:

var monaLisaSize:Rectangle = new Rectangle(0, 0, 175, 150); // The Rectangle's x and y values are ignored.
var bounds:Rectangle       = new Rectangle(0, 0, 143, 143); // The Rectangle's x and y values are ignored.

var result:Rectangle  = RatioUtil.scaleToFill(monaLisaSize, bounds);
monaLisaBitmap.width  = result.width;
monaLisaBitmap.height = result.height;

The results would look similar to this:

The RatioUtil class has many additional methods not covered in this tip. See the documentation for further information.

Comments

Written by Jeffery Nebbett on January 30th, 2009

Used this today for a scrapbooking application. Worked perfectly. Thanks, pal.

Written by sitron on February 17th, 2009

this library contains a lot of cool stuff. thanks!
Concerning this RatioUtil class, i’d add a “snapToPixel” arg so that the returned values are always rounded up.
And maybe a new Dimension class (width/height) could be useful (so that you don’t have to specify values that are not used)
anyway… thanks for sharing.

Written by Aaron Clinger on July 23rd, 2009

Hi Sitron,

That is a great suggestion and we implemented it for the 1.2.0 release.

Written by laaptu on August 9th, 2009

Thanks a lot for this useful library and useful class.as I am using this in my next project.Guys all I have to say is that you all have done a wonderful and marvelous job and i am greatly thankful to you all.

Written by Superman420 on May 21st, 2010

Please

Leave a Reply

Leave a Comment