Embedding images using style sheets and the <mx:Style> tag

Just when you thought I may have run out of Embed examples… Here’s a quick example of embedding an PNG icon using an <mx:Style> block.

Full code after the jump.

The following example creates a simple app with three Button control instances. As you can see the first two buttons both display a checkmark icon even though no explicit icon or style was set on the button. This is because we created a style for the entire Button class, which sets the icon to an embedded asset, “bulletCheck.png”. The third button uses a different icon because we set the styleName property which overrides the icon style with the “bulletWarning.png” asset. Finally, if you click the last button instance, an Alert pop-up displays showing that the default Button styles cascade right down to the nested buttons within the Alert control.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white">

    <mx:Style>
        /* This style applies to all Buttons, including those in Alert controls. */
        Button {
            icon: Embed(source="assets/bulletCheck.png");
        }

        /* Create a custom style class. */
        .bulletWarning {
            icon: Embed(source="assets/bulletWarning.png");
        }
    </mx:Style>

    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;

            private var a:Alert;

            private function showAlert():void {
                a = Alert.show("message");
            }
        ]]>
    </mx:Script>

    <mx:Button label="bug" />
    <mx:Button label="also a bug"/>
    <mx:Button label="Alert.show()" click="showAlert()" styleName="bulletWarning" />

</mx:Application>