Over the past couple of years of doing AS3 coding, it has frustrated me to no end as to why I couldn’t create a new Bitmap object and add Mouse Event Listeners to it.  As I first got into optimizing AS3 display code, trying to shy away from MovieClips everywhere, I started using Sprites more.  As I started learning about the efficiency and pixel-level control of the Bitmap/BitmapData class, I started using those classes more and more.  And every once in a while, I would want to add Mouse Event Listeners to a Bitmap.  Every time during those every once in a while times… it never worked.

I looked at LiveDocs for the Bitmap class.  Was Adobe blind??  Clearly right here:

it showed in the Bitmap class that you could use addEventListener! Instead of figuring out Why, so that I’d know in the future, I would always use a Sprite instead and go on about my happy nerd coding. Today, however, I ran into the same issue and wanted to know Why.

While both Sprite and Bitmap DO allow you to use addEventListener(), it boils down to class heirarchy, which classes each inherit from, and which Events you’re allowed to listen for in each class.

A quick comparison:

The key to this whole Noob Mystery is highlighted in yellow.  While you Can use addEventListener() with Bitmaps, you can only listen for the following Events:

ah… whoops.

Here is an example class if you need both Bitmap/BitmapData’s pixel-level control, and Interactive Mouse/Keyboard events.

[sourcecode lang=”php”]
package zf {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.MouseEvent;

public class InteractiveBitmap extends Sprite {
private var bd:BitmapData;
private var b:Bitmap;

public function InteractiveBitmap( bData:BitmapData ) {
bd = bData;
b = new Bitmap( bd );
addChild( b );
addEventListener( MouseEvent.MOUSE_OVER , onMouseOverHandler , false , 0 , true );
}

private function onMouseOverHandler( evt:MouseEvent ):void {
trace( “MouseOver” );
// insert code to do whatever to the bitmap
}
}
}
[/sourcecode]

The only scenario that causes me trouble still is if I’m using a .png image or an image with some alpha transparency. The MOUSE_OVER event fires when you mouse over ANY part of the Sprite, not specifically the Bitmap. However, just off the top of my head, I’m sure I could whip up something MacGuyver-style using the mouse X/Y coordinates and hitTestPoint on the Bitmap to find exactly when we’re over the Bitmap.

Categories:

0 Comments

Leave a Reply

Avatar placeholder