Resize Background Image with Correct Aspect Ratio in Actionscript 3.0

var _img:Loader = null;
var _picW:Number = 0;
var _picH:Number = 0;

stage.scaleMode    = StageScaleMode.NO_SCALE;
stage.align        = StageAlign.TOP_LEFT;

function LoadBackGround($path:String):void
{
    _img = new Loader();
    _img.load(new URLRequest($path));
   _img.contentLoaderInfo.addEventListener(Event.COMPLETE, Loaded, false, 0, true);
}

function Loaded($e:Event):void
{
    _img.contentLoaderInfo.removeEventListener(Event.COMPLETE, Loaded);

   _picW = _img.height / _img.width;
   _picH = _img.width / _img.height;

   addChild(_img);

   stage.addEventListener(Event.RESIZE, ProportionalScale, false, 0, true);
   ProportionalScale();
}

function ProportionalScale($e:Event=null):void
{
    var $sw:Number    = stage.stageWidth;
    var $sh:Number    = stage.stageHeight;
    var $scale:Number = 0;

if (($sh / $sw) > (_img.height / _img.width))
{
    $scale = _img.width / _img.height;
    _img.height = $sh;
    _img.width = $sh * $scale;

} else {
    $scale =_img.height / _img.width;
   _img.width =  $sw;
   _img.height = $sw * $scale;
}

_img.x = ($sw - _img.width) / 2;
_img.y = ($sh - _img.height) / 2;
}

LoadBackGround("image.jpg");

Advertisements

3 thoughts on “Resize Background Image with Correct Aspect Ratio in Actionscript 3.0

  1. Pingback: Resize Background Image with Correct Aspect Ratio in Actionscript … « action script

  2. Pingback: Resize Background Image with Correct Aspect Ratio in Actionscript … | Flash Designers

  3. Boss…….A salute to you………..Great Shot.

    I just want to made a little contribution by adding a function for the action script 2 guys…………Based on your idea….:)

    Thanks boss once again………..

    function resizer(stager:Object, resizerObj:Object){
    if ((stager.height / stager.width) > (resizerObj._height / resizerObj._width))
    {
    scale = resizerObj._width / resizerObj._height;
    resizerObj._height = stager.height;
    resizerObj._width = stager.height * scale;
    } else {
    scale =resizerObj._height / resizerObj._width;
    resizerObj._width = stager.width;
    resizerObj._height = stager.width * scale;
    }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s