AS3 and images part 2

Previously I talked about using images in AS3. Now I’ve figured out a further enhancement to the procedure I described.

In that previous article I talked about adding an image to the library and instantiating it as a BitmapData object.  Then I talked about creating a Bitmap object, but there’s a problem; in the AS3 reference, on the Bitmap page, there’s this nugget of information:

Note: The Bitmap class is not a subclass of the InteractiveObject class, so it cannot dispatch mouse events. However, you can use the addEventListener() method of the display object container that contains the Bitmap object.

This makes it impossible to turn a Bitmap into, say, a button.  However, there is hope!

Instead of making a Bitmap object, make a Sprite object.  Then fill the Sprite’s graphics member with the bitmap.  Specifically, use the beginBitmapFill(), drawRect() and endFill functions.  Here’s some basic code to get you started:

var t_IconClass:Class = getDefinitionByName("picture0.png") as Class;
var t_BitmapData:BitmapData = new t_IconClass(0, 0);
var t_Sprite:Sprite = new Sprite();
t_Sprite.x = 64;  // Position it wherever you want
t_Sprite.y = 128;
t_Sprite.graphics.beginBitmapFill(t_BitmapData);
t_Sprite.graphics.drawRect(0, 0, t_BitmapData.width, t_BitmapData.height);
t_Sprite.graphics.endFill();
t_Sprite.addEventListener(MouseEvent.MOUSE_DOWN, SpriteClickFunc);
addChild(t_Sprite);

One Response to

  1. Gravatar AS3 and images; Aching Dreams 2 « Chaos Garden via Pingback:

    [...] EDIT: The followup post has more about this and a better way to pull it off. [...]

Leave a Reply »

You must be logged in to post a comment » login.