1. Code
  2. Browser Apps

Building a Better Bitmap Button in AS3


Building a button from a bitmap can be bothersome. If you're using the Flash IDE, you can create a mask to determine which pixels are part of the button and which aren't, but in any other workflow, the entire rectangle containing the bitmap - including any transparent pixels - will be clickable. In this tutorial, you'll learn how to automatically make all transparent pixels unclickable, with just a few lines of code.

Final Result Preview

Let's take a look at the final result we will be working towards:

Notice that the hand cursor only appears when hovering over the actual image; even the gaps in the hair don't cause it to appear. And it's not just for show: the button presses only register when clicking on these areas.

Introduction: What's So Special?

At a first glance, the SWF above appears extremely simple. But look closer! Notice how in the demo above, a button press is only counted if you click somewhere on the actual image. This isn't what would normally happen. Since a bitmap image is always a rectangle, clicking anywhere inside its rectangle normally would count as a button press. Take a look at the example below, where I have outlined the boundary rectangle of our image. Here, you can click anywhere inside the rectangle, including the transparent areas.

As you can see, this is not what we want! For starters, a user could accidentally click the button when he doesn't mean to. In addition, it looks strange when a hand cursor appears over blank space. In this tutorial, you'll learn how to easily correct these problems.

If you aren't already familiar with Object-Oriented Programming or FlashDevelop, I recommend checking out the provided links before starting this tutorial.

Step 1: Getting Started

Open up FlashDevelop and create a new AS3 project (Project > New Project) and call it something like BitmapButtonProj. On the right, open up the src folder and double-click to open it. Add a new class to your project (right-click /src/ > Add > New Class) called BitmapButton

Step 2: Embedding an Image

We now need an image to work with. Here is the one I'm using:

Face image for BitmapButton class

To use a bitmap image (such as a .jpeg file or a .png file) in Actionscript 3, we have to embed it. FlashDevelop makes this easy. After saving the above image somewhere, right-click the lib folder on the right, mouse over Add, and select the Library Asset option.

How to add an image to the library in FlashDevelop

If you want to use your own image, be sure to select one with transparency.

The image you selected will now appear in the lib folder in FlashDevelop. Right-click the image and select Generate Embed Code.

This code embeds the image in to our project. Whenever you embed an image, you need to define on the next line a class that represents the image you embedded. In this case, our class is called ButtonImg.

Step 3: Adding a TextField

Next, we'll add a TextField to display how many times we have clicked the button (which will be added next). Add this to Main():

The code above simply formats the text to display at the top center of our project. Don't miss how we declared our TextField in line 15.

Step 4: Adding the Button

This code should also go in Main():

When we instantiate our BitmapButton in line 36, we pass our embedded image class as a parameter. This will be used by the BitmapButton class. After this, we can simply treat our BitmapButton instance like any other DisplayObject: we can position it and add a MouseEvent.CLICK listener as we normally would.

Step 5: Making the Button Do Something

Add this event handler function to

The final piece of code in our Main class is the event listener for button clicks. In it, we simply add one to the number of clicks, numClicks, and update the text in clicksTextField.

Step 6: The BitmapButton Constructor

Flip over to First, import these classes:

Then, declare these:

You must make sure that the BitmapButton class extends Sprite, since a Bitmap by itself cannot have any mouse interactivity. (The Bitmap class doesn't extend InteractiveObject.)

In our BitmapButton constructor, we accomplish a couple of important things.

  • First, we create a new Bitmap, called image, from the image class passed as a parameter to the constructor.
  • We then add this Bitmap as a child of our Sprite.
  • Next, we set the value of bitmapData to equal the bitmapData of our image.
  • Finally, we add CLICK and MOUSE_MOVE event listeners.

Step 7: The MOUSE_MOVE Event Listener

Our simple looking MOUSE_MOVE event listener is the real brains behind our class. Its main purpose is to determine whether the mouse cursor is over a transparent pixel or not. Let's look at how it does this.

The getPixel32() Function

The first line gets the color and transparency of the pixel that the cursor is currently over. To do this, we use the getPixel32() method of the variable bitmapData (which, remember, is the bitmap data representation of our image).

We must pass an x- and y-coordinate to getPixel32(), so naturally we use the mouse's position.

The call then returns a uint representing the color and transparency of the pixel at the location we supplied.

Colors in Flash are normally treated as a hexadecimal uint in the format RRGGBB. The first two digits represent the amount of red in the color, the next two, green, and the final two, blue. However, getPixel32() provides us with a special uint representing our pixel in the format AARRGGBB. Here, the first two digits represent the alpha, or the amount of transparency, from 00 (clear) to FF (opaque).

So, for example, FF980000 would represent a fully opaque red color, while 00980000 would represent a fully transparent red color. You'll typically see these represented as 0xFF980000 or 0x0098000: the "0x" lets you (and Flash!) know that the number is in hexidecimal (0-f), rather than decimal (0-9).

The Bitwise Unsigned Right Shift Operator

At this point, we have a uint called pixel which is holding the color and alpha of the pixel beneath our mouse in the AARRGGBB format. Unfortunately, this is too much information. All we care about is the transparency of this pixel, or the AA part.

You could write a mathematical expression to obtain this section - in fact, int(pixel/Math.pow(16,6)) would work. This is a somewhat awkward statement, though, and slower performance-wise than another option we have: the bitwise unsigned right shift operator, >>>.

Our variable pixel is just a binary number to Flash. We normally write it in hexadecimal just to make it more readable. Without going into too much detail, every digit of a hexadecimal number can be represented by a string of four binary digits, each one either a 0 or a 1. (So, hexadecimal uses digits 0-f, decimal uses 0-9, and binary uses 0-1.)

Say we have a hexadecimal number, D4. In binary, this would be represented as 11010100. Notice how we use eight binary digits for the binary representation: four times as many as in hexadecimal.

With this is mind, let's examine what the >>> operator actually does. Lets use our previous example, the hexadecimal number D4, or 0xD4 for clarity. Now let's use >>> as so:

Notice that 4 is a normal decimal representation of a number (there's no "0x" at the start). This expression essentially shifts every binary digit in D4 four places to the right, and forgets about any digit that would go off the end of the number.

0xD4, in binary, is 11010100. Apply four shifts, and it becomes 1101. In hexadecimal, this is 0xD.

If you're having trouble understanding this, imagine the binary digits as blocks sitting at the right side of a table. The >>> operator is just like pushing the blocks to the right. Here's our original binary number:

Binary representation of D4 before the bitwise shift is applied

Now here's our new number, after we do 0xD4 >>> 4 :

Binary representation of D4 after the bitwise shift is applied

Notice how after we shifted 0xD4 by 4 bits, we ended up with just 0xD? That's not a coincidence. As said before, each hexadecimal digit is made up of 4 binary digits - so, each time we shift it to the right by 4, we essentially knock one hexadecimal digit off the end. You can probably see where we are going with this!

Back to our pixel, in 0xAARRGGBB format. If we shift it by 24, we are actually shifting by 6 hexadecimal digits. This means the RRGGBB portion gets knocked off, and we end up with just the 0xAA part left, which is our alpha component.

A quick numerical example: Say our pixel is equal to FF980000. In binary, this is 1111 1111 1001 1000 0000 0000 0000 0000. (Each group of 4 digits represents one hexadecimal digit.) When we shift this by 24, we simply end up with 1111 1111, or FF, our two transparency digits.

Take a look at it again:

Okay, the (pixel >>> 24) part makes sense now, but what about the rest?

It's easy. We check whether our alpha component (the result of pixel >>> 24) is greater than the value of THRESHOLD (which is currently set to 0). If it is, useHandCursor and buttonMode are set to true, which will make the cursor change to a hand. This makes our image seem like a button.

If our alpha component is less than or equal to THRESHOLD, the cursor will remain normal, since the mouse is over a (semi-)transparent pixel. Since we have it set to 0, only fully transparent pixels will not be included as part of our button, but you could set this to, say, 0x80, and then it would display the hand cursor for anything that's more than half transparent.

Step 8: The CLICK Event Listener

The final part of our BitmapButton class is the MouseEvent.CLICK event listener. This function will be called every time our image is clicked, no matter whether that pixel is transparent or not. (Changing the mouse cursor as we did before will not affect the actual MouseEvent.)

So, every time there is a click, we check the useHandCursor property. If it is true, this means the mouse is over a normal pixel in our image, and we don't need to do anything. This makes sense - the event will then continue on to the event listener we added in However, if useHandCursor is false, we have to do something to stop the event from continuing on to other event listeners.

For this, we use the stopImmediatePropagation() method that all Event objects have. Simply put, this stops the flow of the event, and no more event listeners will receive it. So, our event listener function in will never be called.

Warning: this could have a nasty side effect - any global event listener will not get the event either. If you are worried about this, you can try adding the line parent.dispatchEvent(e.clone()); after e.stopImmediatePropogation(). While this is beyond the scope of the tutorial, I recommend reading more about the event system here.


This wraps up our tutorial! Thanks for reading, and I hope you have learned something new.

A note of caution when using our BitmapButton class - other MouseEvents will still work as normal, since we only dealt with MouseEvent.CLICK. If you wanted, you could use the same technique we used for MouseEvent.CLICK and apply it to other events, such as MouseEvent.MOUSE_DOWN.

Our BitmapButton class allows us to quickly and easily make great buttons from bitmap images with transparency, as we did in this demo. If you have any questions, I'll be glad to answer them, just leave a comment below.

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.