在Flash中设置已加载图像的尺寸

如何在Flash中设置加载图像的宽度和高度?请求后立即设置尺寸不起作用。宽度和高度保持为零。
var poster:Loader = new Loader();
Stage.addChild(poster);
poster.load(new URLRequest('http://example.com/image.jpg'));
poster.width = 320;
poster.height = 240;
trace(poster.width); // 0
trace(poster.height); // 0
如果我等待片刻,然后设置尺寸,它将起作用。 我按照一些教程的建议,在调整大小之前尝试听
Event.INIT
事件和
Event.COMPLETE
事件。这两件事都没有被触发。
public function theClass() {
    this.poster = new Loader();
    this.poster.contentLoaderInfo.addEventListener(Event.INIT, this.imageLoaded);
    this.poster.contentLoaderInfo.addEventListener(Event.COMPLETE, this.imageLoaded);
    Stage.addChild(this.poster);
    this.poster.load(new URLRequest('http://example.com/image.jpg'));
}

private function imageLoaded(event:Event):void {
    trace('image is loaded');
    this.poster.width = 320;
    this.poster.height = 240;
}
    
已邀请:
在Event.COMPLETE的监听器中是这样做的,所以如果没有触发该事件,则加载器代码中必定存在错误。我注意到你似乎在你发布的代码的顶部创建了一个局部变量“poster”,但是没有在theClass()中声明它,但我不知道这是否会导致你的问题。 此外,通常你等到图像完成加载之后才添加它,但我再次不知道这是否会导致你的问题。 我的意思是,我刚刚编写了以下代码作为最小测试,它工作正常:
public function Main():void {
  var loader:Loader = new Loader();
  loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
  loader.load(new URLRequest("image.png"));
}
private function onComplete(e:Event):void {
  var img:Bitmap = Bitmap(e.target.content);
  this.addChild(img);
  img.width = 100;
  img.height = 100;
}
    
图像是否与您的SWF不同?如果是这样,并且您的Event.COMPLETE侦听器不起作用,则可能是由于安全性异常。具有该文件的服务器必须具有允许访问您的swf所托管的域的crossdomain.xml策略文件,否则您将无法直接操作加载的图像的大小,如jhocking的示例所示。 如果您知道托管图像的服务器上有一个策略文件(通过访问http://site.com/crossdomain.xml并看到它允许您的域或覆盖您的域的通配符),则创建一个loaderContext for你使用的加载器将checkPolicyFile标志设置为true:
var context:LoaderContext = new LoaderContext();
context.checkPolicyFile = true;
this.poster.load(new URLRequest('http://site.com/image.jpg'),context);
在onComplete处理程序中,检查Loader.childAllowsParent以查看您是否有权访问加载程序内容。如果是这样,请设置loader.content.width和loader.content.height。     
向所有负载添加IOErrorEvent侦听器通常是个好主意。如果有问题,那么这将告诉您:
this.poster.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);

function errorHandler(e:IOErrorEvent):void {
trace("Error on load: " + e);
}
如果加载过程中存在问题,这就是您捕获它的方法。     

要回复问题请先登录注册