You’d think adding a Sprite to a Flex component would be easy, right?

Sprites extend DisplayObject, and the addChild() and addChildAt() methods for every Flex component take in an object of type DisplayObject.

Not quite.

From the Adobe® Flex® 3 Language Reference (emphasis added):

Note: While the child argument to the method is specified as of type DisplayObject, the argument must implement the IUIComponent interface to be added as a child of a container. All Flex components implement this interface.

To add a Sprite to a Flex component, you’d have to extend Sprite and implement IUIComponent, which frankly is more effort than its worth.

A far easier solution is to create a custom class that extends UIComponent and acts as a wrapper for the Sprite.

The constructor for such a class would look something like this:

public function SpriteUIComponent (sprite : Sprite)
{
    super ();

    explicitHeight = sprite.height;
    explicitWidth = sprite.width;

    addChild (sprite);
}


Using this custom class, you would add a Sprite to a Flex component like so:

myContainer.addChild (new SpriteUIComponent (mySprite));


Easy.

Advertisements