AS3 Insert an image class and then transfer these images to another class?

For example, right now I have a class called "Balls.as". Here I load 10 different balls. You know, like this:

[Embed(source = "/ball1.png")] [Embed(source = "/ball2.png")] 

The problem is that if I create 5 balls, will these images of balls be inserted 5 * 5 times to the right? Correct me if I am wrong! So even though I can't have a ballimageloading class? It uploads these images once and then to Balls.as. Can I upload any ball that I want at the moment?

+4
source share
2 answers

Best practice is to have an Assets class that will contain static inline images, for example:

 [Embed(source="ball1.png")] public static var BallImage1:Class; 

Then all you have to do is declare a variable for the loaded Bitmap and use it, for example:

 protected var mBall1:Bitmap = new Assets.BallImage1() as Bitmap; 

This will create a Bitmap instance of the uploaded image, and you can add it to the display list. Downloading will occur only once per image, and you will have all the images at your fingertips, accessible from every class that you have.

+9
source

You do not need to “download” them, they are built-in. You just need to create an instance of the images. It is recommended that you have one class that manages shared resources:

 public class TextureAssets { [Embed(source = "../lib/ball1.png")] private static var Ball1:Class; [Embed(source = "../lib/ball2.png")] private static var Ball2:Class; public static var ball1Texture:BitmapData; public static var ball2Texture:BitmapData; public static function init():void { ball1Texture = (new Ball1() as Bitmap).bitmapData; ball2Texture = (new Ball2() as Bitmap).bitmapData; } 

Then you call TextureAssets.init() once (e.g. in Main.as) and when you need bitmapData: use new Bitmap(TextureAssets.ball1Texture)
Thus, your program requires only the memory needed for one bitmapData, instead of having many that end in the same.
If you need to perform operations on bitmapData, keeping the original, you can use:

 var modified:bitmapData = TextureAssets.ballTexture.clone(); 


Also, if you create all the images of balls from the same class, it is recommended to refuse static access and instead initialize bitmapDatas in the constructor, create a new TextureAssets () and call the textures through a variable
(access to the static field is slower than direct (.) access: http://jacksondunstan.com/articles/1690 )

+8
source

All Articles