One important advantage of the Flash Technology (besides it’s platform independency) is the ability to embed media resources into your SWF. If you’ve decided to develop your Flash project using third party IDEs like FDT or Flash Develop, there might be some difficulties to embed resources like images, Flash IDE vector graphics or fonts.
In case of images like JPEG or PNG, fortunately there are some very good loading libraries. These loaders allow you to access external resources during runtime. In most cases this is the recommended technique. But sometimes you absolutely have to deliver a SWF with all or some assets embedded.
For image files there is a very easy way to solve the problem. Here is a sample code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| package {
import flash.display.Sprite;
public class AssetTest extends Sprite {
[ Embed(source="embed_this.png") ]
public static var EmbedThis:Class;
public function AssetTest() {
var img:Sprite = new Sprite();
img.addChild(new EmbedThis);
addChild(img);
}
}
} |
The magic happens in line 5 and 6. We start by using the Embed metatag to tell the compiler where to pick the image from. In this case we want to embed a file called embed_this.png from the same directory where AssetTest is located at. But caution: If AssetTest is not your main or starter class, you will have to define the path of the source relatively to the main class directory or as absolute path.
This is because the compiler starts with one entry file (the main class) and then climbs up and down the package tree to every class referenced by the imports.
If the main class is located at /Main.as and references to /my_classes/AssetTest.as and you want to load an image from /assets/embed_this.png, the Embed metatag in /my_classes/AssetTest.as has to look like [ Embed(source="../assets/embed_this.png") ]. This ../assets/ means one directory level up and then enter assets.
Line 6 defines a new attribute of type Class. This definition has to be placed right below the Embed metatag. By doing so, the compiler will assign the newly embedded data with the attribute of type Class. So this is why we can create a new instance of EmbedThis at line 10 which results in creating a copy of the embedded image.
The compiler is forced by design to accept, that the embedded data capsuled within EmbedThis is a sprout of DisplayObject. This is why we can add it onto a Sprite to display the image we wanted to load.