简体   繁体   中英

Flex embedding an image where the path is based on a bound variable

I am trying to embed an image using an item renderer in my Flex project.

The image path however is a String passed in as a bound variable.

I am aware that

<s:BitmapImage source="@Embed('/../assets/image.png')" />

works because the image is embedded at runtime? (Could someone please clarify this)

How would i go about embedding my bound string, somewhat like this:

<s:BitmapImage source="@Embed('/../assets/{data.image}')" />

Many Thanks

I think a better choice if you'd like to embed the image but find it dynamically at runtime is: Embed all of the images it could be and then grab a reference to it dynamically. We generally use a pattern like this:

public class Icons {
    [Embed(source="icons/icon1.png")]
    public var icon1:Class;
    [Embed(source="icons/icon2.png")]
    public var icon2:Class;
}

Then you can dynamically grab the embedded images from your Icons instance at run-time.

Edit - self contained example - I'll use an item renderer since I think that's what you're doing. Let's assume data.image can be 'plane' 'train' or 'automobile'

<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009" 
            xmlns:s="library://ns.adobe.com/flex/spark" 
            xmlns:mx="library://ns.adobe.com/flex/mx">

    <fx:Script>
        <![CDATA[

            [Embed(source="/assets/icons/plane.png")]
            public var plane : Class;
            [Embed(source="/assets/icons/train.png")]
            public var train : Class;
            [Embed(source="/assets/icons/automobile.png")]
            public var automobile : Class;
        ]]>
    </fx:Script>

    <s:Image source="{this[data.image]}"/>

</s:ItemRenderer>

This is a really simple example and not the BEST way to implement, but you get the idea.

I like embed icons with css files. Then in ItemRenderer you can set css class and get image which you want.

css file or mxml css block:

.icons 
{
    bender: Embed(source="/assets/bender.png");
    /* other icons */
}

In renderer, when you override set data method:

override public function set data(value:Object):void
{
    super.data = value;

    var iconName:String = data.image;

    if ( iconName )
    {
        var cssDecl2:CSSStyleDeclaration = styleManager.getStyleDeclaration(".icons");
        var IconClass:Class = cssDecl2.getStyle( iconName );
        bmImage.source = new IconClass();
    }
}

and bmImage as id s:BitmapImage:

<s:BitmapImage id="bmImage" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM