PhotoHolder - Bitmap/BitmapData Problems
Hello guys, how are you?
I'm trying to create an actionscript 3 class that receives an external image, adds it into a movieclip and adjusts it without corrupting the aspect ratio of the image.
I've tried working with BitmapData and Bitmap only, but can not hit the calculations. Can anyone help me?
Thank you,
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.PixelSnapping;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.geom.Matrix;
import flash.geom.Rectangle;
import flash.net.URLRequest;
import flash.system.LoaderContext;
public class PhotoHolder extends MovieClip
{
private var _loader:Loader;
public function PhotoHolder()
{
}
public function loadPhoto(urlImg:String):void
{
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
_loader.load(new URLRequest(urlImg));
}
private function onError(e:IOErrorEvent):void
{
trace("ERROR!");
}
private function onComplete(e:Event):void
{
var loadedImage:Bitmap = Bitmap(_loader.content);
var bmd:BitmapData = new BitmapData(_loader.content.width, _loader.content.height, true);
bmd.draw(loadedImage, null);
this.holder.addChild(createBitmap(bmd));
}
private function createBitmap(bmd:BitmapData):Bitmap
{
var bitmap:Bitmap = new Bitmap(bmd);
bitmap.smoothing = true;
setSize(bitmap, bmd.width, bmd.height, this.holder.x, this.holder.y);
return bitmap;
}
private function setSize(target:DisplayObject, contentWidth:Number, contentHeight:Number, targetWidth:Number, targetHeight:Number):void
{
var w:Number = targetWidth;
var h:Number = targetHeight;
// maintain aspect ratio
var containerRatio:Number = targetWidth / targetHeight;
var imageRatio:Number = contentWidth / contentHeight;
if (containerRatio < imageRatio) h = w / imageRatio;
else w = h * imageRatio;
target.width = w;
target.height = h;
//centre content - this might change based on your setup
target.x = (targetWidth - w) * .5;
target.y = (targetHeight -h) * .5;
}
}
}