I am very new to actionscript. I want to access already existing BitmapImage in mxml so as to change its source The Bitmap Image already exists im mxml with its id. I dont hav e to create it dynamically only its source is to be set. I have seen some examples but they add image itself dynamically I dont want that. Action Script3 is to be used.
here is the code: Kindly suggest.
<fx:Script>
//code to set image source to url1(a string)
</fx:Script>
<s:Graphic>
<s:BitmapImage
id="ini_image"
source="@Embed('C:/horizontal_red.png')"
width="640"
height="480"
fillMode="scale"
includeIn="ready"
/>
</s:Graphic>
I tried it like this :
var ini_image:BitmapImage = new BitmapImage();
ini_image.source = url;
But it gives error in namespace might be because ii is creating a new object of same type with same name. Which is not allowed. Please correctify me if I am wrong and suggest corrections.
I assume you have more than one state in your application, so you have to take care if the ready state was or not initialized before setting the BitmapImage source. Hope the following code example will solve your problem.
<?xml version="1.0"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
currentState="other">
<s:states>
<s:State name="ready"/>
<s:State name="other"/>
</s:states>
<fx:Script><![CDATA[
private function onButtonClick(event:MouseEvent):void {
currentState = 'ready';
ini_image.source = 'http://lorempixel.com/200/200';
}
]]></fx:Script>
<s:Graphic>
<s:BitmapImage
id="ini_image"
source="http://lorempixel.com/100/100"
width="640"
height="480"
fillMode="scale"
includeIn="ready"
/>
</s:Graphic>
<s:Button click="onButtonClick(event)"/>
</s:Application>
You can also include image in both states and use different image source.
<?xml version="1.0"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
currentState="other">
<s:states>
<s:State name="ready"/>
<s:State name="other"/>
</s:states>
<s:Graphic>
<s:BitmapImage
id="ini_image"
source.other="http://lorempixel.com/100/100"
source.ready="http://lorempixel.com/200/200"
width="640"
height="480"
fillMode="scale"/>
</s:Graphic>
<s:Button click="onToggleStates(event)"/>
<fx:Script><![CDATA[
private function onToggleStates(event:MouseEvent):void {
currentState = currentState == 'other' ? 'ready' : 'other';
}
]]></fx:Script>
</s:Application>