Creating Dynamic button in AS3

In this small tutorial I will explain how to create dynamic button using Flash AS3. I have divided this tutorial into different steps which are as follow:-

Step 1

Create instances SimpleButton, Sprite, TextField and TextFormat classes.

1
2
3
4
5
6
var simpleButton:SimpleButton=new SimpleButton();
var butttonUpState:Sprite=new Sprite();
var butttonOverState:Sprite=new Sprite();
var buttonLabel1:TextField=new TextField();
var buttonLabel2:TextField=new TextField();
var textFormat:TextFormat=new TextFormat();

Step 2

Set text align to center and bold in textFormat instance. Asign “Submit” text to both the TextField instances and set text color, width, height properties and finally set text format to one we created above.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
textFormat.align="center"
textFormat.bold=true;

buttonLabel1.text="Button";
buttonLabel1.textColor=0xFFFFFF;
buttonLabel1.width=50;
buttonLabel1.height=20;
buttonLabel1.setTextFormat(textFormat);

buttonLabel2.text="Button";
buttonLabel2.textColor=0xFFFFFF;
buttonLabel2.width=50;
buttonLabel2.height=20;
buttonLabel2.setTextFormat(textFormat);

Step 3

Draw backgrounds for button Up, Over, Down, and hitTest states. In this tutorial we are using same background for button Up, Down and hitTest states but you can create different background for each.

1
2
3
4
5
6
7
8
9
10
11
with(butttonUpState){
graphics.beginFill(0x333333,1)
graphics.drawRect(0,0,50,20);
graphics.endFill();
}

with(butttonOverState){
graphics.beginFill(0x0066FF,1)
graphics.drawRect(0,0,50,20);
graphics.endFill();
}

Step 4 and Final

Add textfields instances to button Up and button Over state sprites. Assign these sprites to button states like given below and add simplebutton instances to flash movie stage.

1
2
3
4
5
6
7
8
9
butttonUpState.addChild(buttonLabel1);
butttonOverState.addChild(buttonLabel2);

simpleButton.upState=butttonUpState;
simpleButton.overState=butttonOverState;
simpleButton.downState=butttonUpState;
simpleButton.hitTestState=butttonUpState;

addChild(simpleButton);

I hope this simple tutorial will be helpful. Download Source Fla.

Cheers

M

Tags: , ,

Leave a Reply