Fit content into holder from ratio

by chiqui
Fit one thing on another without cropping and centering it
♥0 | Line 39 | Modified 2012-10-31 07:01:19 | MIT License
play

ActionScript3 source code

/**
 * Copyright chiqui ( http://wonderfl.net/user/chiqui )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/eRYv
 */

package {
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    public class FlashTest extends Sprite {
        private var holder:Sprite;
        private var content:Sprite;
        public function FlashTest() {
            holder = new Sprite();
            fillrect(holder, 150, 150);
            content = new Sprite();
            fillrect(content, 30, 60);
            this.addChild(holder);
            this.addChild(content);
            content.addEventListener(MouseEvent.CLICK, onClickContent);
            content.buttonMode = true;
        }
        private function onClickContent(evt:MouseEvent):void{
            makeItFit(content, holder);
        }

        private function makeItFit(cont:Sprite, hold:Sprite):void{
            var holderRatio:Number = hold.width/hold.height;
            var contentRatio:Number = cont.width/cont.height;
            //compare both ratios to get the maximum area
            if(holderRatio < contentRatio){
                cont.width = hold.width;
                cont.scaleY = cont.scaleX;
            }else{
                cont.height = hold.height;
                cont.scaleX = cont.scaleY;
            }
            //now the size is ok, lets center the thing
            cont.x = (hold.width - cont.width)/2;
            cont.y = (hold.height - cont.height)/2;
        }

        private function fillrect(tar:Sprite, ww:int, hh:int):void{
            tar.graphics.beginFill(0xDDDDDD*Math.random(), 1);
            tar.graphics.drawRect(0,0, ww, hh);
            tar.graphics.endFill();
        }

    }
}