Monday, July 21, 2008

Embed assets in Pure ActionScript Applications

After creating a pure actionscript application by following this article, you may also want to add some resources such as images, mp3 and even videos etc. Using embedded assets in actionscript applications is not so straightforward, as stated in Flex documents Flex supports the following syntaxes to embed assets in Flex applications:
  1. [Embed(parameter1, paramater2, ...)] metadata tag
    You use this syntax to embed an asset in an ActionScript file, or in an <mx:script> block in an MXML file.
  2. @Embed(parameter1, paramater2, ...) directive
    You use this syntax in an MXML tag definition to embed an asset.
  3. Embed(parameter1, paramater2, ...) directive
    You use this syntax in an <mx:Style> block in an MXML file to embed an asset.

It's kind of tricky to figure out how to access these embedded assets from actionscripts, I had to spend precious time figuring out how to use these assets from Actionscripts, especially for these actionscript classes under specific packages.

It turns out the solution is fairly straight, what you need to make it work is accessing assets using the correct path, assume that all assets are under assets directory which is a subdirectory of your application root. Here is a sample root directory, the root is helloworld and assets are under assets subdirectory, helloUtil.as is with hello.util package:
helloworld/helloword.as
/assets/bg.jpg
/assets/ball.png
/hello/util/helloUtil.as
now you can access these two images in helloworld.as:
   [Embed(source="assets/bg.jpg")]
public var bgImg:Class;

[Embed(source="assets/ball.png")]
public var ballImg:Class;
Without putting assets in the correct directory you will get the following compiling errors:
   Error: unable to resolve 'bg.jpg' for transcoding

Now if you structure your classes using packages and you also want to access assets directly, then you must access them like:
   [Embed(source="/assets/bg.jpg")]
public var bgImg:Class;

[Embed(source="/assets/ball.png")]
public var ballImg:Class;
Pretty straight, huh, but for a novice it will take sometime to figure this out. And I am hoping you will benefit from it

No comments: