Thursday, November 27, 2008

Flex embed an image as a Class

// Embed the image once and refer to the Class
public var myImage:Class;

This is helpful if you're using the same image in several places, this way you only have to embed it once, and if you change the image file name you only have to change it in one place.

You can also create a Class that holds all the images and you can get an instance of that Class to refer to your images.

For example:

package com.view
 import mx.binding.utils.BindingUtils;

 public class AssetImporter

  private static var instance : AssetImporter;

  //return singleton instance of AssetImporter

  public static function getInstance() : AssetImporter
   if (instance == null)
   instance = new AssetImporter();
   return instance;

  //put your images here
  public var imgOne:Class;

  public var twoLarge:Class;

Then in your mxml script use the following lines

import assets.AssetImporter;
[Bindable] private var assetImporter:AssetImporter = AssetImporter.getInstance();

then to call an image simply refer to the instance

<mx:Image source="{assetImporter.imgOne}"/>

Here is an example of an AssetImporter with view source enabled.

No comments: