logo
468x60-2-495


  • Home
  • Privacy Policy
  • About
search
Jan 18, 2012 Posted on Jan 18, 2012 in Hints and Tips | 10 comments

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 Main.as 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.

public class Main extends Sprite
{
	[Embed(source = "../lib/face.png")]
	private var ButtonImg:Class;

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():

clicksTextField = new TextField();
clicksTextField.width = stage.stageWidth;
clicksTextField.defaultTextFormat = new TextFormat(null, 14, 0, true, false, false, null, null, TextFormatAlign.CENTER);
clicksTextField.text = "Button Presses: " + numClicks;
clicksTextField.mouseEnabled = false;
addChild(clicksTextField);

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():

var button:BitmapButton = new BitmapButton(ButtonImg);
button.x = stage.stageWidth / 2 - button.width / 2;
button.y = stage.stageHeight / 2 - button.height / 2;
addChild(button);
button.addEventListener(MouseEvent.CLICK,onButtonClick);

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 Main.as:

private function onButtonClick(e:MouseEvent):void
{
	numClicks++;
	clicksTextField.text = "Button Presses: " + numClicks;
}

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 BitmapButton.as. First, import these classes:

	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.MouseEvent;

Then, declare these:

		private var bitmapData:BitmapData;
		private const  THRESHOLD:Number = 0;

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.)

public function BitmapButton(ImageData:Class)
{
	var image:Bitmap = new ImageData();
	addChild(image);

	bitmapData = image.bitmapData;

	addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
	addEventListener(MouseEvent.CLICK, onClick);
}

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

	private function onMouseMove(e:MouseEvent):void
	{
		var pixel:uint = bitmapData.getPixel32(mouseX, mouseY);
		useHandCursor = buttonMode = ((pixel >>>24) > THRESHOLD);
	}

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:

0xD4 >>> 4

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:

useHandCursor = buttonMode = ((pixel >>> 24) > THRESHOLD);

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, 0×80, and then it would display the hand cursor for anything that’s more than half transparent.

Step 8: The CLICK Event Listener

private function onClick(e:MouseEvent):void
{
	if (!useHandCursor)
	{
		e.stopImmediatePropagation();
	}
}

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 Main.as. 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 Main.as 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.


Conclusion

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.



View full post on Activetuts+

Jan 3, 2011 Posted on Jan 3, 2011 in Flash Video Training | 1 comment

Create a Flash button (basic)


in this tutorial you will learn how to create a basic button

Dec 24, 2010 Posted on Dec 24, 2010 in Flash Video Training | 25 comments

Create Flash Button


www.websiteguruservices.com How To Create Flash Navigation Buttons In Flash MX.

Dec 21, 2010 Posted on Dec 21, 2010 in Flash Video Training | 9 comments

How to make a rollover flash button


This is a Macromedia Flash Tutorial to make a button that CHANGES COLOUR AS WELL!!!!!!!!! I know, it’s easy but not for everyone out there. It uses basic actionscript. If you don’t understand something, then please write a comment and I’ll get in touch as soon as possible! Made by 8enmero8 and PLEASE! LEAVE A COMMENT AND RATING! Also, Try: extremega.freewebs.com

Dec 16, 2010 Posted on Dec 16, 2010 in Flash Video Training | 2 comments

Flash RollOver Button Tutorial


My First Tutorial :) A RollOver Button Tut. Enjoy + Subscribe!

Page 1 of 712345...»Last »
search search search search search
Find an Article
Categories
  • Flash Video Training
  • Hints and Tips
  • Recommended
Please Support Our Sponsors
Recent Posts
  • Tuts+ Community Meetup in New York!
  • HTML5 Canvas Optimization: A Practical Example
  • Recreate the Cover Flow Effect Using Flash and AS3
  • Drawing Activetuts+ to a Close
  • Intro to Dart: Creating a Marquee
Tag Cloud
2011 ActionScript Active Activetuts+ Adobe animation Basic Basix Best Build Button Character Code Create Creating Critique Custom design Effect Effects Files Flash from Game Guide HTML5 Introduction Macromedia Motion Muzzle part Player Premium Professional Quick Silverlight Simple Text Tool Tutorial Tuts+ Using Video website Workshop
About Our Site:

Hey there and welcome to "Flash Video Training Source", a resource for anybody interested in learning more about Adobe's great tool. We feature educational videos, which will help you master Adobe Flash and help you get to know all of its features. We at "Flash Video Training Source" believe that video training and video... more

Why don't you follow us on Twitter and get the latest video tutorials twitted to your account. Just click on the floating twitter bar to your right!

Go Back In Time
June 2013
M T W T F S S
« Jul    
 12
3456789
10111213141516
17181920212223
24252627282930
Pretty Blank Box
top

Blogroll

  • Development Blog
  • Documentation
  • Plugins
  • Suggest Ideas
  • Support Forum
  • Themes
  • WordPress Planet

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Archives

  • July 2012
  • June 2012
  • May 2012
  • April 2012
  • March 2012
  • February 2012
  • January 2012
  • December 2011
  • November 2011
  • October 2011
  • September 2011
  • August 2011
  • July 2011
  • June 2011
  • May 2011
  • April 2011
  • March 2011
  • February 2011
  • January 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010
  • June 2010
  • May 2010
  • April 2010
Powered by WordPress  |  Designed by Elegant Themes  |  Lightning Fast Hosting by Site 5 Hosting