Custom button with image

Ponty picture Ponty · Feb 9, 2010 · Viewed 9.3k times · Source

Hi i'm trying to create a button in actionscript 3 that will be made by a custom image ( a car.jpg from my HDD ). Is it possible to do that with SimpleButton class ( i mean is there a way to load the image and attach it to the button ?) or is there another way? If i would like to have animation also in the button when let's say i roll over the mouse pointer from the button what do i have to do?

ps: i would like to use only actionscript 3 ( i mean all the project is done as a .as file that is linked to Document class ).

Answer

a--m picture a--m · Feb 9, 2010

Although George Profenza already pointed the best solution under the comment if feel curious how you could implement the SimpleButton class you might want to take a look into th as3 document reference examples:

adobe livedocs - SimpleButton Example

I have also wrote a simple example that only makes a "simple button" in a "complicated button" but makes use of SimpleButton class, so you can take a look how you can extend the class, and give to each state it's own graphic. Here is the code:

// this goes in your app
var button:MySimpleButton = new MySimpleButton();
addChild(button);

MySimpleButton.as

package  
{
    import flash.display.DisplayObject;
    import flash.display.SimpleButton;
    import flash.display.Sprite;

    public class MySimpleButton extends SimpleButton 
    {
        private var upAlpha : Number = 1;
        private var overAlpha : Number = 0.5;

        public function MySimpleButton(upState : DisplayObject = null, overState : DisplayObject = null, downState : DisplayObject = null, hitTestState : DisplayObject = null)
        {
            upState = new ButtonImgDisplayState( upAlpha);
            overState = new ButtonImgDisplayState( overAlpha);
            downState = new ButtonImgDisplayState( upAlpha);
            hitTestState = new ButtonImgDisplayState( upAlpha);

            super(upState, overState, downState, hitTestState);
        }
    }
}

ButtonImgDisplayState.as

package  
{
    import flash.display.Loader;
    import flash.display.Sprite;
    import flash.net.URLRequest;

    public class ButtonImgDisplayState extends Sprite 
    {

        public function ButtonImgDisplayState(_alpha:Number)
        {
            var my_loader : Loader = new Loader();
            my_loader.load(new URLRequest("car.jpg"));
            addChild(my_loader);

            this.alpha = _alpha;
        }
    }
}

The thing about the SimpleButton is to spare you to set listeners, but you are obligated to go around the states that are separated DisplayObjects making you button a more rigid thing when dealing with transitions between states.

Hope you find this useful.