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.

4 comments
Comments feed for this article
June 24, 2008 at 5:02 am
burnhh
hey there,
an alternative way of adding DisplayObjects to Containers is using the methods rawChildren.addChild and rawChildren.addChildAt although Adobe seems to do it the same way you proposed.
http://www.restlessthinker.com/blog/?p=59
regards,
burn
June 24, 2008 at 7:17 am
Nick Schneble
Nice one!
You can definitely do it either way – I just found it easier to get a DisplayObject inside a UIComponent and then never have to deal with it again!
October 20, 2008 at 7:00 am
Bookmarks about Sprites
[...] – bookmarked by 4 members originally found by toursexbrazil on 2008-10-04 Adding Sprites to Flex Components http://userflex.wordpress.com/2008/06/12/sprite-uicomponent/ – bookmarked by 5 members originally [...]
September 13, 2009 at 6:58 am
Flex and Sprites « Experts-Monologue
[...] full description can be read this informative blogpost Adding Sprites to Flex Components Filed under: Uncategorized Leave a comment Comments (0) Trackbacks (0) ( subscribe to comments [...]