Setting a background image on a Spark Application in Flex 4

The following example shows how you can add a background image to a Flex 4 Spark Application by creating a custom skin with a BitmapGraphic and setting the skinClass style in MXML, CSS, or ActionScript.

Full code after the jump.

The following example(s) require Flash Player 10 and the Adobe Flex 4 SDK. To download the Adobe Flash Builder 4 trial, see www.adobe.com/products/flex/. To download the latest nightly build of the Flex 4 SDK, see opensource.adobe.com/wiki/display/flexsdk/Download+Flex+4.

For more information on getting started with Flex 4 and Flash Builder 4, see the official Adobe Flex Team blog.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2009/03/22/setting-a-background-image-on-an-fxapplication-in-flex-gumbo/ -->
<s:Application name="Spark_Application_skinClass_test"
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/halo"
        skinClass="skins.CustomApplicationSkin">
    <s:layout>
        <s:BasicLayout />
    </s:layout>
 
    <s:RichEditableText id="sdkVer"
            editable="false"
            textAlign="center"
            fontSize="72"
            horizontalCenter="0"
            verticalCenter="0"
            width="100%"
            initialize="sdkVer.text = mx_internal::VERSION;" />
 
</s:Application>

The custom skin class, skins/CustomApplicationSkin.mxml, is as follows:

View skins/CustomApplicationSkin.mxml

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2009/03/22/setting-a-background-image-on-an-fxapplication-in-flex-gumbo/ -->
<s:Skin name="CustomApplicationSkin"
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        alpha.disabled="0.5" >
    <s:states>
        <s:State name="normal" />
        <s:State name="disabled" />
    </s:states>
 
    <fx:Metadata>
    <![CDATA[ 
        [HostComponent("spark.components.Application")]
    ]]>
    </fx:Metadata> 
 
    <!-- fill -->
    <s:BitmapImage id="img"
            source="@Embed('image1.jpg')"
            resizeMode="scale"
            smooth="true"
            left="0" right="0"
            top="0" bottom="0" />
 
    <s:Group id="contentGroup" left="0" right="0" top="0" bottom="0" minWidth="0" minHeight="0" />
 
</s:Skin>

You can also set the skinClass style in an external .CSS file or <Style/> block, as seen in the following example:

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2009/03/22/setting-a-background-image-on-an-fxapplication-in-flex-gumbo/ -->
<s:Application name="Spark_Application_skinClass_test"
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/halo">
    <s:layout>
        <s:BasicLayout />
    </s:layout>
 
    <fx:Style>
        @namespace s "library://ns.adobe.com/flex/spark";
 
        s|Application {
            skinClass: ClassReference("skins.CustomApplicationSkin");
        }
    </fx:Style>
 
    <s:RichEditableText id="sdkVer"
            editable="false"
            textAlign="center"
            fontSize="72"
            horizontalCenter="0"
            verticalCenter="0"
            width="100%"
            initialize="sdkVer.text = mx_internal::VERSION;" />
 
</s:Application>

Or, you can set the skinClass style using ActionScript, as seen in the following example:

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2009/03/22/setting-a-background-image-on-an-fxapplication-in-flex-gumbo/ -->
<s:Application name="Spark_Application_skinClass_test"
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/halo">
    <s:layout>
        <s:BasicLayout />
    </s:layout>
 
    <fx:Script>
        <![CDATA[
            import skins.CustomApplicationSkin;
 
            protected function btn_click(evt:MouseEvent):void {
                setStyle("skinClass", CustomApplicationSkin);
            }
        ]]>
    </fx:Script>
 
    <s:Button id="btn"
            label="Set skin class"
            click="btn_click(event);"
            x="10"
            y="10" />
 
    <s:RichEditableText id="sdkVer"
            editable="false"
            textAlign="center"
            fontSize="72"
            horizontalCenter="0"
            verticalCenter="0"
            width="100%"
            initialize="sdkVer.text = mx_internal::VERSION;" />
 
</s:Application>

This entry is based on a beta version of the Flex 4 SDK and therefore is very likely to change as development of the Flex SDK continues. The API can (and will) change causing examples to possibly not compile in newer versions of the Flex 4 SDK.

26 thoughts on “Setting a background image on a Spark Application in Flex 4

  1. Denis,

    The new Gumbo FxApplication tag doesn’t have a backgroundImage style. It allows the FxApplication class can be a lot simpler and have less code/overhead, and thankfully skinning is very easy so creating a custom FxApplication skin with a background image can be done in a few lines.

    Peter

  2. Wow, this has to be the most over-complicated software update of all time. Unbelievable. Only programmers could think any of these changes make any sense. Something as simple as a background image now takes a programmer.

    Silverlight never looked so good.

  3. I’m afraid i agree that this is badly over-complicated. a large number of casual apps just need a simple backgroundImage property. a whole separate file for a background image is unreasonable.

  4. Solution #1: Modify the Spark Application skin’s backgroundRect skin part’s fill property at runtime to a BitmapFill object with an embedded image:

    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
            xmlns:s="library://ns.adobe.com/flex/spark"
            xmlns:mx="library://ns.adobe.com/flex/mx"
            creationComplete="init();">
     
        <fx:Script>
            <![CDATA[
                import mx.core.FlexGlobals;
                import mx.graphics.BitmapFill;
                import mx.graphics.BitmapFillMode;
     
                import spark.skins.spark.ApplicationSkin;
     
                [Embed("pattern_149.gif")]
                protected const BgImg:Class
     
                protected function init():void {
                    var bmpFill:BitmapFill = new BitmapFill();
                    bmpFill.source = BgImg;
                    bmpFill.fillMode = BitmapFillMode.REPEAT;
                    ApplicationSkin(skin).backgroundRect.fill = bmpFill;
                }
            ]]>
        </fx:Script>
     
        <s:Button id="btn"
                label="Spark Button"
                width="200" height="100"
                horizontalCenter="0" verticalCenter="0" />
     
    </s:Application>
  5. Solution #2: Extend the default Spark Application skin and override the backgroundRect skin part’s fill property with an embedded image:

    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
            xmlns:s="library://ns.adobe.com/flex/spark"
            xmlns:mx="library://ns.adobe.com/flex/mx"
            skinClass="skins.CustomBitmapApplicationSkin">
     
        <s:Button id="btn"
                label="Spark Button"
                width="200" height="100"
                horizontalCenter="0" verticalCenter="0" />
     
    </s:Application>

    And the custom Spark Application skin, skins/CustomBitmapApplicationSkin.as, is as follows:

    package skins {
        import mx.graphics.BitmapFill;
        import mx.graphics.BitmapFillMode;
        import spark.skins.spark.ApplicationSkin;
     
        public class CustomBitmapApplicationSkin extends ApplicationSkin {
            [Embed("pattern_149.gif")]
            protected const BgImg:Class
     
            public function CustomBitmapApplicationSkin() {
                super();
                var bmpFill:BitmapFill = new BitmapFill();
                bmpFill.source = BgImg;
                bmpFill.fillMode = BitmapFillMode.REPEAT;
                backgroundRect.fill = bmpFill;
            }
        }
    }
    1. Solution #3: Create a better default Spark Application skin:

      <?xml version="1.0" encoding="utf-8"?>
      <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
              xmlns:s="library://ns.adobe.com/flex/spark"
              xmlns:mx="library://ns.adobe.com/flex/mx"
              skinClass="skins. CustomBitmapApplicationSkin2">
       
          <fx:Style>
              @namespace s "library://ns.adobe.com/flex/spark";
       
              s|Application {
                  backgroundImage: Embed("pattern_149.gif");
              }
          </fx:Style>
       
          <s:Button id="btn"
                  label="Spark Button"
                  width="200" height="100"
                  horizontalCenter="0" verticalCenter="0" />
       
      </s:Application>

      And the custom Spark Application skin, skins/CustomBitmapApplicationSkin2.mxml, is as follows:

      <?xml version="1.0" encoding="utf-8"?>
      <s:Skin xmlns:fx="http://ns.adobe.com/mxml/2009"
              xmlns:s="library://ns.adobe.com/flex/spark"
              xmlns:fb="http://ns.adobe.com/flashbuilder/2009"
              alpha.disabledStates="0.5">
          <s:states>
              <s:State name="normal" />
              <s:State name="disabled" stateGroups="disabledStates" />
              <s:State name="normalWithControlBar" stateGroups="controlBarStates" />
              <s:State name="disabledWithControlBar" stateGroups="disabledStates,controlBarStates" />
          </s:states>
       
          <fx:Metadata>
              [HostComponent("spark.components.Application")]
          </fx:Metadata> 
       
          <fx:Script fb:purpose="styling">
              <![CDATA[
                  override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
                      backgroundRect.setStyle("backgroundAlpha", getStyle("backgroundAlpha"));
                      backgroundRect.setStyle("backgroundColor", getStyle("backgroundColor"));
       
                      if (getStyle("backgroundImage")) {
                          backgroundRect.setStyle("backgroundImage", getStyle("backgroundImage"));
                          backgroundRect.setStyle("backgroundImageFillMode", "repeat");
                      }
       
                      super.updateDisplayList(unscaledWidth, unscaledHeight);
                  }
              ]]>
          </fx:Script>
       
          <!-- fill -->
          <!--- 
          A rectangle with a solid color fill that forms the background of the application.
          The color of the fill is set to the Application's backgroundColor property.
          -->
          <s:BorderContainer id="backgroundRect"
                  backgroundColor="#FFFFFF"
                  borderVisible="false"
                  left="0" right="0" top="0" bottom="0" />
       
          <s:Group left="0" right="0" top="0" bottom="0">
              <s:layout>
                  <s:VerticalLayout gap="0" horizontalAlign="justify" />
              </s:layout>
       
              <!--- Application Control Bar -->
              <s:Group id="topGroup"
                      minWidth="0" minHeight="0"
                      includeIn="controlBarStates" >
       
                  <!-- layer 0: control bar highlight -->
                  <s:Rect left="0" right="0" top="0" bottom="1" >
                      <s:stroke>
                          <s:LinearGradientStroke rotation="90" weight="1">
                              <s:GradientEntry color="0xFFFFFF" />
                              <s:GradientEntry color="0xD8D8D8" />
                          </s:LinearGradientStroke>
                      </s:stroke>
                  </s:Rect>
       
                  <!-- layer 1: control bar fill -->
                  <s:Rect left="1" right="1" top="1" bottom="2" >
                      <s:fill>
                          <s:LinearGradient rotation="90">
                              <s:GradientEntry color="0xEDEDED" />
                              <s:GradientEntry color="0xCDCDCD" />
                          </s:LinearGradient>
                      </s:fill>
                  </s:Rect>
       
                  <!-- layer 2: control bar divider line -->
                  <s:Rect left="0" right="0" bottom="0" height="1" alpha="0.55">
                      <s:fill>
                          <s:SolidColor color="0x000000" />
                      </s:fill>
                  </s:Rect>
       
                  <!-- layer 3: control bar -->
                  <s:Group id="controlBarGroup"
                          left="0" right="0" top="1" bottom="1"
                          minWidth="0" minHeight="0">
                      <s:layout>
                          <s:HorizontalLayout paddingLeft="10" paddingRight="10"
                                  paddingTop="7" paddingBottom="7"
                                  gap="10" />
                      </s:layout>
                  </s:Group>
              </s:Group>
       
              <s:Group id="contentGroup"
                      width="100%" height="100%"
                      minWidth="0" minHeight="0" />
          </s:Group>
       
      </s:Skin>

      True, not as light weight as the other solutions, but switching the backgroundRect skin part from a plain Rect object to a BorderContainer object allows you to easily set background colors, background alphas, and more importantly background image and background image fill modes.

  6. Whoever made it this hard to simply set background image should quit his job and see if he can succeed in making bread, chopping wood or something…

  7. Anyone can actually show how to scale the background image with the browser window resizing? None of these examples allow to do so!

  8. This is great, except ‘resizeMode’ is not a valid property anymore. How do you keep the background image centered and keep it from scaling on browser resize?

    1. @Greg,

      There are a few examples above, but this should also work:

      <?xml version="1.0" encoding="utf-8"?>
      <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                     xmlns:s="library://ns.adobe.com/flex/spark"
                     xmlns:mx="library://ns.adobe.com/flex/mx"
                     skinClass="skins.CustomApplicationSkin">
          <s:controlBarContent>
              <s:Button id="sdkVer" initialize="sdkVer.label = mx_internal::VERSION;" click="System.setClipboard(sdkVer.label);" />
          </s:controlBarContent>
       
          <s:DropDownList id="ddl"
                          labelField="fontName"
                          requireSelection="true"
                          horizontalCenter="0" y="20">
              <s:dataProvider>
                  <s:ArrayList source="{Font.enumerateFonts(true).sortOn('fontName')}" />
              </s:dataProvider>
          </s:DropDownList>
       
      </s:Application>

      And the custom Spark Application container skin, skins/CustomApplicationSkin.mxml, is as follows:

      <?xml version="1.0" encoding="utf-8"?>
      <spark:ApplicationSkin xmlns:fx="http://ns.adobe.com/mxml/2009"
                             xmlns:s="library://ns.adobe.com/flex/spark"
                             xmlns:spark="spark.skins.spark.*">
       
          <fx:Script>
              <![CDATA[
                  import mx.graphics.BitmapFill;
                  import mx.graphics.BitmapFillMode;
       
                  [Embed("skins/pattern_149.gif")]
                  protected const BG_FILL:Class;
       
                  override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
                      var bmpFill:BitmapFill = new BitmapFill();
                      bmpFill.source = BG_FILL;
                      bmpFill.fillMode = BitmapFillMode.REPEAT;
                      backgroundRect.fill = bmpFill;
                      super.updateDisplayList(unscaledWidth, unscaledHeight);
                  }
              ]]>
          </fx:Script>
       
      </spark:ApplicationSkin>

      Peter

  9. Peter…

    I can get the bg image to display, but once I do, my content vanishes. I even have the contentGroup s:Group container in there. I’m trying this code with a Flex Mobile Project if that matters.

  10. I got this to work (thanks a million for all of these posts bte) but Flex give a warning;
    “This compilation unit did not have a factoryClass specified in Frame metadata to load the configured runtime shared libraries. To compile without runtime shared libraries either set the -static-link-runtime-shared-libraries option to true or remove the -runtime-shared-libraries option.”
    How do you set the option to true?

Comments are closed.