Actionscript 3 animation using png's, reload or hide? - actionscript-3

using flash and actionscript 3 I want to use a lot of png's as animation. I currently use a Loader object to load these images. But now I am wondering what the best way would be to show these animations:
1.
Every time a have to show a new png, I could use the loader to load it, just having one loader:
var image:Loader = new Loader();
And using this function everytime a new image is used as part of the animation:
image.load(new URLRequest(location));
2.
I could also create dozens of loaders, one for every image, and hide every loader except the one that I want shown. When I want to animation to continue, I hide the current one and show the next one. This would mean creating A LOT of Loader objects.
Which way would be the best? Or is there a third even better way to do this?

The Flash IDE's main purpose is precisely this... I know many people hate it to develop, and with good reasons, but I really think that the ideal tool for animating in Flash is the Flash IDE.

Do the below:
public class ImageLoader { // Singleton class for explanation
private static var imageLoader:Loader = new Loader(); // 1 loader only
private static var currentImage:Bitmap = null; // currently attached image
public static function Initialize():void {
imageLoader.contentLoaderInfo.addEventListener( Event.COMPLETE, Rsc_Loaded );
}
public static function RenderImage( url:String ):void {
imageLoader.load( new URLRequest( url ) );
}
private static function Rsc_Loaded( eEvent:Event ):void {
if ( null != currentImage ) { // if previous bitmap was attached to stage
currentImage.parent.removeChild( currentImage ); // remove it
}
currentImage = eEvent.target.content; // Bitmap is loaded
// attach the content to stage for rendering
GetMainApp().stage.addChild( currentImage );
}
}
// then inside your main app. do below
// load image 1 and add it to stage
imageLoader.load("img1.png");
// time to animate to img2.png
imageLoader.load("img2.png");
this is not the most efficient method, but you can add a cache to pre-cache all the images and just attach them to stage. Or if you are hardcore, can readup about the BitmapData class and perform your own pixel manipulation.

Related

How to loop SWF file loaded with Loader?

I want to loop a swf file that has been loaded with via the Loader class in AS3.
My code looks as following:
public class MyLoader extends MovieClip {
public function MyLoader() {
var myLoader:Loader = new Loader();
var url:URLRequest = new URLRequest("external-movie.swf");
myLoader.load(url);
myLoader.contentLoaderInfo.addEventListener("complete", function() {
});
addChild(myLoader);
}
}
From what I understand the Loader has no event for when the embedded movie is finished? Is there a way to figure that out? It must not be a AS3 implementation. I just want a movie that has been exported from Indesign to run in a loop. Thanks in advance
Especially when you have little experience programming you should avoid dirty shortcuts as they'll only get you a lot of trouble. So avoid anonymous function and avoid using string in place of static event variables.
This being said, if your loaded movie has its own timeline then it will be converted into a MovieClip. Also that movie is not embedded but loaded and that's a big difference.
Keep a reference of that movie and the loader:
private var theLoadedMovie:MovieClip;
private var myLoader:Loader;
Listen for the INIT event instead of the COMPLETE event (movies with timeline start to play when their first frame is loaded "INIT", the COMPLETE event fires when the whole movie is loaded).
myLoader = new Loader();
var url:URLRequest = new URLRequest("external-movie.swf");
myLoader.load(url);
myLoader.contentLoaderInfo.addEventListener(Event.INIT, handleInit);
In your handleInit method keep a reference of that movie:
theLoadedMovie = myLoader.content as MovieClip;
addChild(theLoadedMovie);
theLoadedMovie.addEventListener(Event.ENTERFRAME, handleEnterFrame);
in your handleEnterFrame method check the movie progress to know when it has ended:
if(theLoadedMovie.currentFrame == theLoadedMovie.totalFrames)
{
//movie has reached then end
}

The most lightweight button implementation in actionscript 3.0 [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Since button is one of the most popular GUI components this question becomes hot when we talk about memory usage. Especially when you have tons of buttons in your application.
So how you can implement a button that uses minimum CPU and memory resources and yes, acts like normal button with mouse up, down and hand pointer behavior implemented. Label text is also required.
If you want to have tonnes of buttons with text and graphics, using the least amount of RAM and processing power, you should be using Bitmaps.
This gets a lot more complicated and involves your own preparation of the following:
A font in the form of a sprite sheet.
Classes that manage rendering text onto a Bitmap using that sprite sheet.
Bitmaps don't respond to MouseEvents, so you'll need to architect your own system for managing mouse input on the Bitmaps.
Firstly, lets take a look at the base memory consumption for some of the DisplayObjects that you would think we would be best using. This is our testing method:
function ram(type:Class):void
{
trace(getSize(new type()));
}
And this is the test:
ram(Sprite); // 408
ram(Shape); // 236
ram(TextField); // 1316
In your case, drawing 1000 buttons would result in over 1,724,000 bytes of memory being used.
Now let's look at what we will be using:
1x Bitmap acting as a Canvas that holds all buttons: 236 bytes.
1x BitmapData representing the initial state of every button.
1x BitmapData representing the rollover state of every button.
1x BitmapData storing our text as a sprite sheet for use by all buttons.
Each BitmapData will be quite large in memory consumption, and varies greatly depending on its content. But the trick here is that we only use one and refer to its content for every button that we want to draw.
I've set up a small amount of code to get you started. You still need to implement a click manager which loops over all the buttons and works out which is most relevant to trigger a click, as well as rendering the text on the buttons.
Here's the Button class:
public class BitmapButton
{
private var _text:String;
private var _position:Point = new Point();
public function BitmapButton(text:String)
{
_text = text;
}
public function render(canvas:BitmapData, font:BitmapData, state:BitmapData):void
{
canvas.copyPixels(state, state.rect, _position);
// Use font argument to render text.
// For you to implement.
}
public function get position():Point{ return _position; }
}
And here's the class that will manage rendering those buttons:
public class ButtonCanvas extends Bitmap
{
private var _fontSprite:BitmapData;
private var _baseState:BitmapData = new BitmapData(100, 30, false, 0xFF0000);
private var _overState:BitmapData = new BitmapData(100, 30, false, 0x00FF00);
private var _buttons:Vector.<BitmapButton> = new <BitmapButton>[];
private var _checkRect:Rectangle = new Rectangle();
public function ButtonCanvas(width:int, height:int)
{
bitmapData = new BitmapData(width, height, true, 0x00000000);
// Replace with actual loaded sprite sheet.
_fontSprite = new BitmapData(1, 1);
}
public function add(button:BitmapButton):void
{
_buttons.push(button);
}
public function render():void
{
if(stage === null) return;
bitmapData.lock();
for each(var i:BitmapButton in _buttons)
{
_checkRect.x = i.position.x;
_checkRect.y = i.position.y;
_checkRect.width = _baseState.width;
_checkRect.height = _baseState.height;
if(_checkRect.contains(mouseX, mouseY))
{
// Use roll over style.
// Need to implement depth check so you can't roll over buttons
// that fall behind others.
i.render(bitmapData, _fontSprite, _overState);
}
else
{
i.render(bitmapData, _fontSprite, _baseState);
}
}
bitmapData.unlock();
}
public function get buttons():Vector.<BitmapButton>{ return _buttons; }
}
And a small test:
var canvas:ButtonCanvas = new ButtonCanvas(stage.stageWidth, stage.stageHeight);
addChild(canvas);
for(var i:int = 0; i < 20; i++)
{
var button:BitmapButton = new BitmapButton("Hello");
button.position.x = Math.random() * stage.stageWidth;
button.position.y = Math.random() * stage.stageHeight;
canvas.add(button);
}
stage.addEventListener(MouseEvent.MOUSE_MOVE, update);
function update(e:MouseEvent):void
{
canvas.render();
}
canvas.render();
Now that you've read all of that, I'll point out that it's really unlikely you need to anywhere near this extreme, unless you have some type of game that revolves around buttons and buttons are actually particles that get generated every frame in the 100's. Using a standard Sprite + TextField is perfectly fine in almost all cases.
One of the traditional patterns is using Sprite + TextField
Adobe recommends using Shape instead of Sprite (when it makes sense):
a Sprite object is a display object container, whereas a Shape object is not. For this reason, Shape objects consume less memory than Sprite objects that contain the same graphics.
It would be great to use Shape, and we can do it, but we can not add TextField on it.
Now lets look at TextField inheritance chain:
TextField: InteractiveObject -> DisplayObject -> EventDispatcher -> Object
We can observe that a TextField object is much lighter than a Sprite object - wrong. Using only TextField will be lighter than using TextField + Sprite. I came up with this decision:
import flash.events.MouseEvent;
import flash.filters.BevelFilter;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.ui.Mouse;
import flash.ui.MouseCursor;
public class Button extends TextField
{
private static const MOUSE_UP:Array =
[new BevelFilter(2, 45, 0xEEEEEE, .7, 0x444444, .7, 1, 1)];
private static const MOUSE_DOWN:Array =
[new BevelFilter(2, 225, 0xEEEEEE, .7, 0x444444, .7, 1, 1)];
private static const TEXT_FORMAT:TextFormat =
new TextFormat('Verdana', 12, 0xDDDDDD,
null, null, null, null, null, 'center');
public function Button(label:String, color:int = 0x166488)
{
width = 80;
height = 20;
background = true;
backgroundColor = color;
selectable = false;
defaultTextFormat = TEXT_FORMAT;
text = label;
addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
addEventListener(MouseEvent.ROLL_OVER, onMouseRollOver);
addEventListener(MouseEvent.ROLL_OUT, onMouseRollOut);
onMouseUp();
}
private function onMouseRollOut(e:MouseEvent):void
{
Mouse.cursor = MouseCursor.AUTO;
}
private function onMouseRollOver(e:MouseEvent):void
{
Mouse.cursor = MouseCursor.BUTTON;
}
private function onMouseDown(e:MouseEvent):void
{
filters = MOUSE_DOWN;
}
private function onMouseUp(e:MouseEvent = null):void
{
filters = MOUSE_UP;
}
//kill method
}
This code draws nice lightweight button BUT I can not adjust vertical position of a text label so height of this button depends of font-size. Another issue is that I cann't move the text label a bit down-right when somebody clicks it.
Any ideas will be appreciated.
We can observe that a TextField object is much lighter than a Sprite object. That's completely incorrect. A Sprite uses 408 bytes in memory whereas a TextField uses 1316
Yes TextField will consume way more memory.
I would create the label text in a graphics program and create a sprite menu class.
TextField is not really lightweight but a pretty powerful class. If you want user input then TextField is the way to go.
Avoid any of the buttons built into the Flash library and just start simple and build functionality on the sprite class.
If you really want to optimize your interface, reduce the event handlers and any sort of transparency. This might just be good Flash advice in general but often overlooked.
Make a function that gets called every frame, tick();, think();, update(); something like this. Add a single event handler to the main class and within that call your update() function within the menu elements.
Adding a dozen event handlers to your menu elements is not only cumbersome but unsightly.
I would venture to say a sprite with the buttonMode property set to true for the "hand pointer" and then functions to handle the ROLL_OVER and ROLL_OUT MouseEvents.

Loading google maps static images into flash

I'm trying to load images from google maps static images api into flash. When I attempt to load them flash complain about sandbox issues. Even after I try and load the policy file from google.
Security.loadPolicyFile("http://maps.googleapis.com/crossdomain.xml");
Is there any way around this? or is it simply impossible to load images in this fashion?
var loader1:Loader = new Loader();
var lctx1:LoaderContext = new LoaderContext(true);
loader1.contentLoaderInfo.addEventListener(Event.INIT, doImgInit);
loader1.load(new URLRequest("http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=14&size=600x400&maptype=satellite&sensor=false&scale=4"), lctx1);
private function doImgInit(evt:Event):void
{
trace("DO IT")
// get a reference to the LoaderInfo object in which the image is loaded
var lInfo:LoaderInfo = evt.target as LoaderInfo;
// this variable is used as reference to the image in the end.
var dO:DisplayObject;
// try to access the "content" property of the loader, if it works, there is a crossdomain.xml file.
try{
dO = lInfo.loader.content;
}
// if there wasn't one, we need to put the loader inside another object in order to manipulate it
catch(err:SecurityError)
{
// create a new Sprite to contain the loaded image
var sprt:Sprite = new Sprite();
// add the loader to the sprite
sprt.addChild(lInfo.loader);
// get a reference to this sprite in the dO variable
var dO:DisplayObject = sprt as DisplayObject;
}
// from here on you can do anything to the dO variable, rotate it, draw it unto a bitmapData, move it around..
// but first don't forget to add to to some container that is on the stage so you can see it!
}

How to convert loaded SWF to bitmapdata?

I use the loader class to load some png files to the stage. The function that is called after the file is loaded is something similar to this:
private function IconLoaded(e:Event):void
{
percentLoaded_txt.visible = false;
iconLoader = Loader(e.target.loader);
icone = Bitmap(iconLoader.content);
icone.smoothing = true;
var _icon: imgBox;
_icon = new imgBox(_MAX_WIDTH, _MAX_HEIGHT, icone,0);// new imgHelper(_bitmap);
_icon.x = _main.cena.width/2;
_icon.y = _main.cena.height/2;
addChild(_icon);
}
imgBox is a class that auto resize the bitmap and allow also to add border for example...
My code works fine, to load PNG files. But I want also to be able to load swf files.
How can I do this?
Thanks.
You will need to make a copy of the loaded SWF into a Bitmap.
function copyIt(obj:DisplayObject):Bitmap {
var bd:BitmapData = new BitmapData( obj.width, obj.height );
bd.draw(obj);
return new Bitmap(bd);
}
var bmpCopy:Bitmap = copyIt(mySWF);
addChild(bmpCopy);
You can't load a swf as a bitmap data because they are totally distinct types. What you can do is load a swf and add it as a child of a movie clip to show its content.
This link shows how to load a swf. After loading it, you just need to add this as a child of a MovieClip and add this movieclip to the stage to show its content.

Controlling FPS of a loaded swf

I'm working on a flash app where I load multiple swf's. But the problem is that they have different framerates (12/25/30). If I add 2 swf's they both play at 25fps. I found numerous topic about this but I can't get it to work (in AS3). Does anyone know why it doesn't work and how to make it working?
public class MainClass extends MovieClip
{
var loader:Loader = new Loader();
var request:URLRequest;
var mcMedia:MovieClip = new MovieClip();
MovieClip.prototype.setFrameRate = function(frameRate:Number)
{
var mc:MovieClip = this;
if (mc.tweenFaster != null)
{
Timer(mc.tweenFaster).stop();
}
mc.tweenFaster = new Timer(1000/frameRate);
mc.tweenFaster.addEventListener(TimerEvent.TIMER, timelineFaster);
mc.tweenFaster.start();
function timelineFaster(event:TimerEvent = null)
{
if (mc.currentFrame == mc.totalFrames)
{
mc.tweenFaster.stop();
mc.gotoAndStop(1);
}
else
{
trace(mc.currentFrame);
mc.nextFrame();
}
event.updateAfterEvent();
}
}
public function MainClass()
{
configureListeners();
request = new URLRequest("data/7/7.swf");
try
{
loader.load(request);
}
catch (error:Error)
{
trace("Unable to load requested document.");
}
}
private function configureListeners():void
{
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
loader.contentLoaderInfo.addEventListener(Event.OPEN, openHandler);
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler);
loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
loader.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}
private function completeHandler(event:Event):void
{
loader.content.scaleX = 550/event.target.width;
loader.content.scaleY = 400/event.target.height;
mcMedia.addChild(loader);
mcMedia.setFrameRate(12);
addChild(mcMedia);
}
In as3, if you're just looking to change the framerate, use stage.frameRate = 12; or whatever;
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/Stage.html#frameRate
In AS3, while you can use prototypes, you generally don't. I'd rewrite your setFrameRate function (which is badly named, shouldn't it be more.. tweenFaster, or matchFrameRate or something?)
I'd make a helper function like this:
package util{
//imports
public class TweenFasterMC extends MovieClip{
public var mc:MovieClip;
public function matchFrameRate(frameRate:Number):void
{
if (tweenFaster != null)
{
Timer(mc.tweenFaster).stop();
}
tweenFaster = new Timer(1000/frameRate);
tweenFaster.addEventListener(TimerEvent.TIMER, timelineFaster);
tweenFaster.start();
}
function timelineFaster(event:TimerEvent = null):void
{
if (currentFrame == totalFrames)
{
tweenFaster.stop();
gotoAndStop(1);
}
else
{
trace(currentFrame);
nextFrame();
}
event.updateAfterEvent();
}
}
Also, clean up your event listeners, that strong timer event listener will cause a lot of problems if you have a lot of mc's your applying this functionality to.
As far as I know all MovieClips in one flash player instance (sharing the same 'stage') will run at the same speed - there is no way to have two clips running at different speeds. So to adjust the speed you have to resort to calling gotoAndStop() on all MovieClips in the loaded clip at the right time - that won't be fun.
Code along the lines that quoo is showing will only work if the loaded swf contains just 1 MovieClip (no nesting) as far as I can see.
It seems to me that the most likely reason why this wouldn't work is that it requires every clip you load to be a simple, completely non-dynamic animation that loops for ever. If the loaded content is that simple, why not just adjust it to look better at 30fps? (If it's extremely long, a JSFL script could automate the process of adding extra frames.) Alternately, if the content isn't that simple, then attempting to change its timing by calling nextFrame from elsewhere is not going to give you what you want.
With all that said, if you're sure this is what you want to do but you're getting 0 as a return for currentFrame in your loaded content, are you sure they are AS3 SWFs? If they aren't, AS3/AS2 interoperation is a hairy subject that will warrant reading up on.
This is a real hassle, I've been scouring the net for an answer. I have particles following a path, and I want to change the speed that these particles follow the path dynamically, without changing the whole movie. just the particles movie clip.
I've tried greensock, but, that doesn't really work like i need.. i'd think there would be something that you can change dynamically for each mc, but, no dice.
the stage.frameset is only for the whole movie... argggggggg..... sucks..