Search tutorials

Loading a different image each time using Local Shared Objects - Page 3
Unique image
For the unique image approach you'll store the value of current in the LSO so that the next time, you can increase this value, and load the next image in the array. If you've reached the last element of the array, you have to start over again.
When you have the correct value, load the corresponding image:
var current:uin = lso.data.current;
current++;
if (current >= total)
current = 0;
loadImage(current);
Here's the complete code (Main.as):
package
{
import flash.display.Bitmap;
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.net.SharedObject;
import flash.net.URLRequest;
public class Main extends Sprite
{
private var images:Array;
private var total:uint;
private var loader:Loader;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
images = new Array("800px-Wintersports_terrain_park_S-rail_GP1393.jpeg", "snowboard2.jpg", "snowboard12.jpg", "snowboarding15_800.jpg", "xtreme-snowboarding.jpg");
total = images.length;
getImage();
}
/**
* find the current image that should be loaded
*/
private function getImage():void
{
// create a LSO identified by "unique"
var lso:SharedObject = SharedObject.getLocal("unique");
var current:uint;
// does "current" exist already
if (lso.data.current != undefined)
{
// grab it
current = lso.data.current;
// increase it
current++;
// reset it if required
if (current >= total)
current = 0;
}
// if it doesn't, initialize it
else
{
current = 0
}
// store current in the LSO
lso.data.current = current;
// load the appropriate image
loadImage(current);
}
/**
* load the current image
* @param current
*/
private function loadImage(current:uint):void
{
loader = new Loader();
var img:String = images[current];
var request:URLRequest = new URLRequest("images/" + img);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadImgComplete);
loader.load(request);
}
/**
* when the image finishes loading
* add it to the display list
* @param e
*/
private function loadImgComplete(e:Event):void
{
var bm:Bitmap = Bitmap(loader.content);
addChild(bm);
}
}
}
» Level Intermediate |
Added: 2011-02-28 Rating: 1 Votes: 1 |
» Author |
Nuno Mira has been a Flash Developer for 9 years. He loves teaching, and learning. When he isn't coding he may be surfing or snowboarding. |
» Download |
Download the files used in this tutorial. |
Download (491 kb) |
» Forums |
More help? Search our boards for quick answers! |