照片加载顺序搞乱as3

时间:2013-02-08 20:19:43

标签: actionscript-3 flash loader

我创建了一个容器(或一个动画片段),它将按顺序添加照片并在舞台上显示。但是,由于文件大小不同,它会先添加最小的文件大小的照片。我怎么能解决这个问题。请参阅下面的示例代码

// image0.jpg -> 3k
// image1.jpg -> 2k
// image2.jpg -> 1k
// image3.jpg -> 2k
// image5.jpg -> 1k

var photoPath:Array = new Array();
var photoContainer:MovieClip = new MovieClip();

photoPath.push('image0.jpg');
photoPath.push('image1.jpg');
photoPath.push('image2.jpg');
photoPath.push('image3.jpg');
photoPath.push('image4.jpg');

for(var i = 0; i < photoPath.length; i++)
{
    var loader:Loader = new Loader();
    loader.load(URLRequest(photoPath[i]));
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, photoLoaded);
}

function photoLoaded(e:Event):void
{
    photoContainer.addChild(e.target.content);
}

//output will looks like (image2,image5,image1,image3,image0) instead of 0,1,2,3,4,5

2 个答案:

答案 0 :(得分:1)

有很多方法可以解决这个问题,可能最简单的改进当前代码的方法是在实例化时将Loader添加到displaylist。这将保证它们以正确的顺序放置在photoContainer中。如果你绝对需要位图本身在displaylist中而不是加载器本身,你可以在你的photoLoaded方法中解决这个问题:

import flash.display.Loader;

var photoPath:Array = new Array();
var photoContainer:MovieClip = new MovieClip();

photoPath.push('image0.jpg');
photoPath.push('image1.jpg');
photoPath.push('image2.jpg');
photoPath.push('image3.jpg');
photoPath.push('image4.jpg');

for(var i = 0; i < photoPath.length; i++)
{
    var loader:Loader = new Loader();
    photoContainer.addChild(loader);  //add the loader to photoContainer
    loader.load(new URLRequest(photoPath[i]));
    //you only actually have to listen for complete below if you want to replace the loader with its contents 
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, photoLoaded);
}

function photoLoaded(e:Event):void
{
    var loader:Loader = e.target.loader;
    var index:int = photoContainer.getChildIndex(loader);
    // this will add the contents of the loader in the same order the loader was originally added
    photoContainer.addChildAt(loader.content, index);
    photoContainer.removeChild(loader);
}

答案 1 :(得分:0)

只需按照数组中给出的顺序加载照片并将其添加到容器中:

var photoPath:Array = new Array();
var photoContainer:MovieClip = new MovieClip();
var i:int = 0;

photoPath.push('image0.jpg');
photoPath.push('image1.jpg');
photoPath.push('image2.jpg');
photoPath.push('image3.jpg');
photoPath.push('image4.jpg');

loadPhoto(i);

function loadPhoto(i:int):void
{
    var loader:Loader = new Loader();
    loader.load(new URLRequest(photoPath[i]));
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, photoLoaded);
}

function photoLoaded(e:Event):void
{
    photoContainer.addChild(e.target.content);
    trace(e.target.url); // Verify
    if(i<photoPath.length-1) loadPhoto(++i);
}

输出:

image0.jpg
image1.jpg
image2.jpg
image3.jpg
image4.jpg