Flex Chronicles #9: No Library? No Worries.

Someone who uses ActionScript heavily in Flex, I embed my graphics in Flex (since it doesn’t have a Library like Flash) using code, like so:

[Embed(source="../../../images/dice.swf" symbol="d4")]
static public var d4_img:String;

If it was just a PNG or JPEG, I could remove the symbol attribute. That is for SWF files, which I like to use heavily; it removes the amount of images I have in my Flex application folders; 1 SWF vs. dozens of images folders containing dozens of images.

The other way is to merely embed it on the image itself:

<mx:Image source="@Embed(‘../../../images/dice.swf#d6’)" width="41" height="46" />

The problem is, combining these techniques will cause collisions; Flex will not compile your app saying that the image was already imported.

To solve this, I created a library of my own, in ActionScript. The technique goes something like this. You should not use _global variables in Flash, thus, you use static classes with static, public variables. All you then have to do is import the static class, and you can then access it’s variables. If you make 1 class, called “Library”, and do all of your image embedding in it, you can then consolidate, and self-contain all of your image assets into 1 file, thus avoiding collisions where other files try to embed assets already embedded elsewhere.

So, an example class would be:

class com.jxl.Library
        [Embed(source="../../../images/dice.swf" symbol="d4")]
        static public var d4_img:String;
        [Embed(source="../../../images/dice.swf" symbol="d6")]
        static public var d6_img:String;
        [Embed(source="../../../images/dice.swf" symbol="d8")]
        static public var d8_img:String;
        [Embed(source="../../../images/dice.swf" symbol="d10")]
        static public var d10_img:String;
        [Embed(source="../../../images/dice.swf" symbol="d12")]
        static public var d12_img:String;
        [Embed(source="../../../images/dice.swf" symbol="d20")]
        static public var d20_img:String;
        [Embed(source="../../../images/dice.swf" symbol="d100")]
        static public var d100_img:String;

Example usage for ActionScript:

import com.jxl.Library;

private var image_ldr:mx.controls.Image;
image_ldr.contentPath = Library.d4_img;

Example usage for Flex tags:

<mx:Image source="{com.jxl.Library.d4_img}" width="39" height="46" />

This will hopefully help prevent collisions, keep your library assets organized, and make them easily accessible.

One Reply to “Flex Chronicles #9: No Library? No Worries.”

  1. While this works, the problem is that you’re unable to use this in design mode. You’d have to run it to preview it, which, while not terrible, leads me to believe there must be a better solution.

Comments are closed.