Martin
Martin

Reputation: 11336

Load random image from XML file

I have almost non-existanl knowledge on AS3/Flash CS5.

I need to load a random image from an XML file with the list of urls.

Every time I load the movie, it should load a random image.

Any idea how to do this?

Upvotes: 0

Views: 828

Answers (1)

pho
pho

Reputation: 25489

I'm assuming this is what your xml file looks like:

<images>
    <image url="http://url_to_image/1.png" width="100" height="100" />
    <image url="http://url_to_image/2.png" width="100" height="100" />
    <image url="http://url_to_image/3.png" width="100" height="100" />
    <image url="http://url_to_image/4.png" width="100" height="100" />
    <image url="http://url_to_image/5.png" width="100" height="100" />
</images>

And here's what you'll do to get a random one from those:

private function randomImage(imagesXML:XML):Object {
    var imageList:XMLList=imagesXML.image;
    var imageCollection:XMLListCollection=new XMLListCollection(imageList);
    var random:int=Math.floor(Math.random() * imageCollection.length);
    var r:Object={};
    r.url=xmlCollection[random].@url;
    r.width=Number(xmlCollection[random].@width);
    r.height=Number(xmlCollection[random].@height);
    return r;
}

And here's how you would call it:

private var x:XML=<images>
        <image url="http://url_to_image/1.png" width="100" height="100" />
        <image url="http://url_to_image/2.png" width="100" height="100" />
        <image url="http://url_to_image/3.png" width="100" height="100" />
        <image url="http://url_to_image/4.png" width="100" height="100" />
        <image url="http://url_to_image/5.png" width="100" height="100" />
    </images>;

var img:Object=randomImage(x);

Now you have img.url, img.width, img.height

Upvotes: 1

Related Questions