해결책 : SWFLoader 내부에 있는 로직을 착출해서 필요한 부분만 골라 쓴다.
소스 : 실행 애플리케이션 소스 NOTE : 이 소스를 실행해 보려면 실행 폴더에 Test.jpg 파일이 있어야 한다.
ImageLoader 클래스
package
{
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLRequest;
/**
* Sprite를 확장한 클래스로서 source로 지정된 디스플레이 객체를 add하는 로더 클래스
*
*/
public class ImageLoader extends Sprite
{
public function ImageLoader() {
super();
}
private var _source:Object;
private var child:DisplayObject;
private var loader:Loader;
private var _contentWidth:Number;
private var _contentHeight:Number;
/**
* 로더에 로드시킬 대상 디스플레이 객체
**/
public function set source(value:Object):void {
_source = value;
if (child && this.contains(child)) {
this.removeChild(child);
}
if (loader && this.contains(loader)) {
this.removeChild(loader);
}
if (value is Class) {
child = new value();
child.addEventListener(Event.ADDED_TO_STAGE,addedHandler);
try {
addChild(child);
} catch (e:Error) {
trace(e.toString(),"failed to add child!");
}
} else if (value is String) {
var loader:Loader = new Loader();
loader.load(new URLRequest(value.toString()));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,completeHandler,false,0,true);
addChild(loader);
}
}
private function addedHandler(event:Event):void {
event.currentTarget.removeEventListener(Event.ADDED_TO_STAGE,addedHandler);
measure(event.currentTarget);
}
private function completeHandler(event:Event):void {
event.currentTarget.removeEventListener(Event.COMPLETE,completeHandler);
measure(event.currentTarget.content);
}
private function measure(target:Object):void {
if (!isNaN(contentWidth)) target.width = contentWidth;
if (!isNaN(contentHeight)) target.height = contentHeight;
}
/**
*
* @private
**/
public function get source():Object {
return _source;
}
/**
* 로더에 포함된 디스플레이 객체
**/
public function get content():* {
return child;
}
public function set contentWidth(value:Number):void {
_contentWidth = value;
if (child) child.width = value;
if (loader) loader.loaderInfo.content.width = value;
}
public function get contentWidth():Number {
return _contentWidth;
}
public function set contentHeight(value:Number):void {
_contentHeight = value;
if (child) child.height = value;
if (loader) loader.loaderInfo.content.height = value;
}
public function get contentHeight():Number {
return _contentHeight;
}
}
}
ImageLoader 클래스는 간단히 이미지 경로 URL 또는 클래스 형태의 이미지를 source로 입력받는다. 하는 일은 contentWidth와 contentHeight를 입력 받아 이에 맞게 이미지의 크기를 조절해 주는 일이다. 여기서는 굳이 이벤트를 발생시키지는 않았지만, 필요하면 setter와 getter 메소드에서 이벤트를 발생시키도록 클래스를 수정할 수도 있을 것이다. ActionScript 원리
Sprite 클래스는 빈 Sprite일 경우 width와 height 값이 무시된다. Sprite 가 빈 Sprite라는 건, 자식이 없다는 것이다. 이 클래스는 문자열이 소스로 들어올 경우 Loader 클래스를 사용하고, 클래스가 소스로 들어올 경우 클래스의 생성자를 호출해 이를 addChild하고 있고, 각각의 경우를 구별해 이벤트 리스너를 처리하는 방식으로 소스의 크기를 정하고 있다.





