O'Reilly logo

Introducing Starling by Thibault Imbert

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Button

Starling natively supports the concepts of buttons. Here is the signature of the Button constructor:

public function Button(upState:Texture, text:String="", downState:Texture=null)

By default, the Button class creates an internal TextField to support labels and the text is centered inside the button. In the following code, we create a simple button out of an embedded bitmap that we use as a skin:

package
{

    import flash.display.Bitmap;

    import starling.display.Button;
    import starling.display.Sprite;
    import starling.events.Event;
    import starling.textures.Texture;

    public class Game extends Sprite
    {

        [Embed(source = "../media/textures/button_normal.png")]
        private static const ButtonTexture:Class;

        public function Game()
        {
            addEventListener(Event.ADDED_TO_STAGE, onAdded);
        }

        private function onAdded (e:Event):void
        {
            // create a Bitmap object out of the embedded image
            var buttonSkin:Bitmap = new ButtonTexture();

            // create a Texture object to feed the Button object
            var texture:Texture = Texture.fromBitmap(buttonSkin);

            // create a button using this skin as up state
            var myButton:Button = new Button(texture, "Play");

            // createa container for the menu (buttons)
            var menuContainer:Sprite = new Sprite();

            // add the button to our container
            menuContainer.addChild(myButton);

            // centers the menu
            menuContainer.x = stage.stageWidth - menuContainer.width >> 1;
            menuContainer.y = stage.stageHeight - menuContainer.height >> 1;

            // show the button
            addChild(menuContainer);
        }

    }
}

Note that we use here the

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required