Playing a video with flex, AS3 - actionscript-3

I am currently trying to make a game on flex and one of the problems I ran in to is how to play a short animation at the beginning. This is what I have so far:
Game.mxml
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
name="Game"
backgroundColor="#000000"
horizontalAlign="center"
creationComplete="Init();"
enterFrame="UpdateFrame();"
paddingLeft="0"
paddingTop="0"
paddingBottom="0"
paddingRight="0"
width="800" height="600">
<mx:Script>
<![CDATA[
include "Game.as";
]]>
</mx:Script>
<mx:Canvas id="gamePanel" x="0" y="0" width="100%" height="100%" mouseDown="MouseDown(event)" mouseUp="MouseUp(event)" mouseMove="MouseMoved(event)"/>
</mx:Application>
and Game.as
import flash.display.*;
import flash.events.*;
import flash.external.ExternalInterface;
import mx.events.*;
import mx.controls.*;
[Embed(source="MyVideoClip.flv")] private var MyVideoClip:Class;
public function Init():void
{
var MyVideo:Video = new Video(800, 600);
addChild(MyVideo);
var qNetConnection:NetConnection = new NetConnection();
qNetConnection.connect(null);
var qNetStream:NetStream = new NetStream(qNetConnection);
MyVideo.attachNetStream(qNetStream);
qNetStream.client = new Object();
qNetStream.play(MyVideoClip);
}
private function UpdateFrame():void
{
}
private function MouseDown(event:MouseEvent):void
{
}
private function MouseUp(event:MouseEvent):void
{
}
private function MouseMoved(event:MouseEvent):void
{
}
I am rather new to Flex and AS3 so most of this code was ripped off web tutorials. Whenever I try to compile it I get: 'Error: 'MyVideoClip.flv' does no have a recongnized extention, and a mimeType was not provided. Error: unable to transcode 'MyVideoClip.flv''
If I remove the 'embed' line and replace MyVideoClip with "MyVideoClip.flv" in the play() function, the code compiles with no errors, but when I open the SWF all I get is a black screen. What am I doing terribly wrong?
Thanks in advance!!

Try setting the mime-type, e.g.:
[Embed(source = "MyVideoClip.flv", mimeType = "application/octet-stream")]

You embedded the video file (its bytes) into the output SWF. So now NetStream must play from a bytes source. Just set a byteArray as equal to new MyVideoClip(); and append to NetStream.
Try this...
[Embed(source="MyVideoClip.flv", mimeType="application/octet-stream")] private var MyVideoClip:Class; //# embed the FLV's bytes
public var VideoClipBytes : ByteArray;
public var MyVideo:Video;
public var qNetConnection:NetConnection;
public var qNetStream:NetStream;
public function Init():void
{
VideoClipBytes = new MyVideoClip() as ByteArray; //# fill a byte Array with embedded bytes
qNetConnection = new NetConnection(); qNetConnection.connect(null);
qNetStream = new NetStream(qNetConnection);
qNetStream.client = new Object();
MyVideo = new Video(800, 600);
MyVideo.attachNetStream(qNetStream);
addChild(MyVideo);
qNetStream.play(null); //# play mode is now bytes
qNetStream.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN); //# ready for new audio/video data
qNetStream.appendBytes( VideoClipBytes ); //# add bytes to decoder queue (playback)
}
PS : I made some of your variables as public so later you can access & control them from any other functions. Remember if you make var inside a public function it stays valid only in that one function and doesn't exist to other functions. Best make such vars as publicly available to all functions.

Related

Dynamically display text in Flex, ActionScript 3

I've been having problems displaying text in ActionScript 3 using Flex SDK 4.6. Any method I try results in no change or a black screen; here is my project code and attempts.
MyProject.mxml is simply and mx:Application tag with the relevant parts being
<mx:Script>
<![CDATA[
include "MyProject.as"; //simply running my project file
]]>
</mx:Script>
and
<mx:Canvas id="gamePanel" x="0" y="0" width="100%" height="100%"/> //defining the canvas
In MyProject.as I have
import flash.display.*;
import flash.events.*;
import mx.events.*;
import mx.controls.*;
import Game;
public static const SCREEN_WIDTH:int = 960;
public static const SCREEN_HEIGHT:int = 720;
private var initializationCompleted:Boolean = false;
public var screenBuffer:BitmapData;
public var game:Game;
public function setup():void {
screenBuffer = new BitmapData(SCREEN_WIDTH, SCREEN_HEIGHT, false, 0x00000000);
game = new Game(SCREEN_WIDTH, SCREEN_HEIGHT, screenBuffer);
initializationCompleted = true;
}
private function updateFrame():void {
if (!initializationCompleted) {
return;
}
draw();
gamePanel.graphics.clear();
gamePanel.graphics.beginBitmapFill(screenBuffer, null, false, false);
gamePanel.graphics.drawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
gamePanel.graphics.endFill();
}
private function draw():void {
game.update();
}
And in Game.as, I simply draw everything using the BitmapData class, and then copy everything to the screenBuffer:
screenBuffer.copyPixels(myBitmap, new Rectangle(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), new Point(0,0));
(This is only the relevant code - I trimmed as much as possible to leave a "Minimal, Complete, and Verifiable example")
Now I have been having problems displaying text in my project. I know that TextField is a subclass of flash.display.Sprite which can be added to the canvas. Whenever I try using something like
var txtHello:TextField = new TextField();
txtHello.text = "Hello World";
gamePanel.addChild(txtHello)
this either changes nothing (if used in setup(), I'm assuming I'm drawing over it or else it is never displayed) or causes a black screen (if used anywhere in updateFrame(), I'm assuming I'm creating infinite sprites).
I have tried instead, creating a new file named "TextWithImage.as" with the contents
//this is ripped off the adobe help page
package {
import flash.display.Sprite;
import flash.text.*;
public class TextWithImage extends Sprite {
private var myTextBox:TextField = new TextField();
private var myText:String = "Hello World";
public function TextWithImage() {
addChild(myTextBox);
myTextBox.text = myText;
}
}
}
importing it in MyProject.as, and then using it as
gamePanel.addChild(new TextWithImage());
to the same effect as my previous attempt.
What is the simplest way to display text in Flex/AS3? Any help is appreciated, and thank you in advance!
There's a trick. Flex components, albeit having the same addChild method derived from DisplayObjectContainer class, cannot actually add regular Flash content - Shape, Sprite, MovieClip, TextField, Bitmap - directly. More to that, they don't produce any runtime error, which I personally think they totally could to not confuse new people.
Flex component can only addChild classes that extend the basic UIComponent class. At the same time, UIComponent can addChild regular Flash content. Thus you do it as following:
var proxyContainer:UIComponent = new UIComponent;
var txtHello:TextField = new TextField;
txtHello.text = "Hello World";
proxyContainer.addChild(txtHello);
gamePanel.addChild(proxyContainer);

Actionscript 3 and Flex 4 Zoom Gesture on SWFLoader

I seem to be having issue with Zoom Gestures on a SWFLoader. I have an swf file which is a floor plan of a home, I want the user to be able to zoom in and out with two finger touch, the following code below is what I tried and does not work. When I test on a touchscreen, it does not zoom when I place two fingers inside the SWF and try to zoom in.
<s:SWFLoader id="floorplanImage" source="#Embed('assets/test2.swf')" width="100%" height="100%" smoothBitmapContent="true" horizontalAlign="center" />
here is my actionscript 3 code
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
Multitouch.inputMode = MultitouchInputMode.GESTURE;
import flash.events.Event;
public var selectedItem:Object;
public function init(): void
{
floorplanImage.addEventListener(TransformGestureEvent.GESTURE_ZOOM , onZoom);
}
public function onZoom (e:TransformGestureEvent):void{
floorplanImage.scaleX *= e.scaleX;
floorplanImage.scaleY *= e.scaleY;
}
Please Help!
UPDATE
I am going the route of gestouch, however with this code, I CANNOT zoom in or out on an SWF. With a regular image it works, but not with SWF unless I am missing something. Here is my code:
<mx:Script>
<![CDATA[
import org.gestouch.events.GestureEvent;
import org.gestouch.gestures.TransformGesture;
private var _zoom:TransformGesture;
[Embed(source="assets/test2.swf")]
private var myClass:Class;
private var myMovieClip:MovieClip;
private function initModel():void
{
myMovieClip = MovieClip(new myClass());
swfcontainer.addChild(myMovieClip);
_zoom = new TransformGesture(swfcontainer);
_zoom.addEventListener(org.gestouch.events.GestureEvent.GESTURE_BEGAN, onGesture);
_zoom.addEventListener(org.gestouch.events.GestureEvent.GESTURE_CHANGED, onGesture);
}
private function onGesture(event:org.gestouch.events.GestureEvent):void
{
const gesture:TransformGesture = event.target as TransformGesture;
var matrix:Matrix = swfcontainer.transform.matrix;
// Panning
matrix.translate(gesture.offsetX, gesture.offsetY);
swfcontainer.transform.matrix = matrix;
if (gesture.scale != 1)
{
// Scale and rotation.
var transformPoint:Point = matrix.transformPoint(swfcontainer.globalToLocal(gesture.location));
matrix.translate(-transformPoint.x, -transformPoint.y);
matrix.scale(gesture.scale, gesture.scale);
matrix.translate(transformPoint.x, transformPoint.y);
swfcontainer.transform.matrix = matrix;
}
}
]]>
</mx:Script>
<mx:Image id="swfcontainer" horizontalAlign="center" width="100%" height="100%" />
When I use this with a regular image, it still does not work properly...it doesn't keep the image center when zooming, it does not let me zoom in, only out and when I first use it, it moves the image to the right. HOW COME THIS IS SOOOOOO HARD?
Please keep in mind I am very very new to Adobe Flex and Actionscript, so please make your answers as clear as possible.
Your code has no problem,I'll explain what I did for my project. Maybe it helped, i have Window design app and i load SWF into starling and have issue
with zoom and pan;
FYI: I Use starling and load SWF file with native overlay in starling and zoom pan work
_mLoader = new Loader();
var mRequest:URLRequest = new URLRequest("drawer.swf" + "?nf=" + getTimer());
_mLoader.contentLoaderInfo.addEventListener(flash.events.Event.COMPLETE, onCompleteHandler);
_mLoader.load(mRequest);
private function onCompleteHandler(loadEvent:flash.events.Event):void
{
_mLoader.contentLoaderInfo.removeEventListener(flash.events.Event.COMPLETE,
Starling.current.nativeOverlay.addChild(LoaderInfo(loadEvent.currentTarget).content);
}
And because the library touching the flash was weak i use above lib,and this is to Strong
first of all test above lib maybe that's work Without Starling
better GESTURE lib than flash lib
my zoom code with this lib
var _zoom:
_zoom = new TransformGesture(this);
_zoom.addEventListener(GestureEvent.GESTURE_BEGAN, onGesture);
_zoom.addEventListener(GestureEvent.GESTURE_CHANGED, onGesture);
private function onGesture(event:org.gestouch.events.GestureEvent):void
{
const gesture:TransformGesture = event.target as TransformGesture;
var matrix:Matrix = container_movieclip.transform.matrix;
if (container_movieclip.scaleX!=1 || container_movieclip.scaleY!=1)
{
matrix.translate(gesture.offsetX, gesture.offsetY);
container_movieclip.transform.matrix = matrix;
}
if (gesture.scale != 1)
{
var transformPoint:Point = matrix.transformPoint(container_movieclip.globalToLocal(gesture.location));
matrix.translate(-transformPoint.x, -transformPoint.y);
matrix.scale(gesture.scale, gesture.scale);
matrix.translate(transformPoint.x, transformPoint.y);
container_movieclip.transform.matrix = matrix;
}
}
I hope I could help
simply your issue solved if you changed multiinputMethod to touchpoint
Multitouch.inputMode=MultitouchInputMode.TOUCH_POINT;

AIR app:How to load swf from server

My app structure is below:
(local)
Login.swf
(server)
Main.swf
assets1.swf
assets2.swf
Login.swf -> Main.swf (OK!)
Main.swf -> assets1&2.swf (fail!, downloaded but not trigger complete event)
-progress event: bytes:loaded==total
Why?
How can i load assets from server using Main.swf?
I found somebody say it is crossdomain problem...then how to solve?
var _loader:Loader = new Loader();
var context:LoaderContext = new LoaderContext();
context.allowCodeImport = true;
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_complete_handler);
_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loader_progress_handler);
_loader.loadBytes(_urlloader.data,context);
Thanks!
BE AWARE:
On mobile it only works on Android... iOS due to a security policy does not permit to load an swf inside another one.
Said that you can surerly load an SWF.
First of all we need to understand if you can download the SWF bytearray using the URLLoader.
if yes you can load the swf in a two step routine..
hope this help :)
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
showStatusBar="false"
creationComplete="downloadSwf()">
<fx:Script>
<![CDATA[
import mx.core.FlexGlobals;
import mx.events.CloseEvent;
import mx.events.FlexEvent;
import mx.managers.SystemManager;
import spark.components.Application;
private function downloadSwf():void {
// load the file with URLLoader into a bytearray
sfwLoader.visible = false;
var loader:URLLoader = new URLLoader();
// binary format since it a SWF
loader.dataFormat=URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, onSWFLoaded);
loader.addEventListener(IOErrorEvent.IO_ERROR, cantConnect);
//load the file
loader.load(new URLRequest("url"));
}
private function cantConnect(e:IOErrorEvent):void
{
var loader:URLLoader=URLLoader(e.target);
loader.removeEventListener(Event.COMPLETE, onSWFLoaded);
loader.removeEventListener(IOErrorEvent.IO_ERROR, cantConnect);
// error handling
return;
}
private function onSWFLoaded(e:Event):void {
// remove the event
var loader:URLLoader=URLLoader(e.target);
loader.removeEventListener(Event.COMPLETE, onSWFLoaded);
loader.removeEventListener(IOErrorEvent.IO_ERROR, cantConnect);
// add an Application context and allow bytecode execution
var context:LoaderContext=new LoaderContext();
context.allowLoadBytesCodeExecution=true;
// set the new context on SWFLoader
sfwLoader.loaderContext = context;
sfwLoader.addEventListener(Event.COMPLETE, loadComplete);
// load the data from the bytearray
sfwLoader.load(loader.data);
}
// your load complete function
private function loadComplete(completeEvent:Event):void {
sfwLoader.removeEventListener(Event.COMPLETE, loadComplete);
var swfApplication:* = completeEvent.target.content;
var sysmgr:SystemManager = (swfApplication as SystemManager);
sysmgr.addEventListener(FlexEvent.APPLICATION_COMPLETE, swfAppComplete);
}
private function swfAppComplete(event:FlexEvent):void {
sfwLoader.visible = true;
var sysmgr:SystemManager = (event.currentTarget as SystemManager);
sysmgr.removeEventListener(FlexEvent.APPLICATION_COMPLETE, swfAppComplete);
var swfApp:Application = (sysmgr.application as Application);
if (!swfApp.hasOwnProperty("version")) {
return;
}
// version is a public property in the main of the loaded application
var verion:String = swfApp["version"];
swfApp.addEventListener(Event.CLOSE, appClose);
}
private function appClose(e:Event):void
{
sfwLoader.unloadAndStop(true);
NativeApplication.nativeApplication.exit();
}
private function closeApp(e:CloseEvent):void
{
try{
(FlexGlobals.topLevelApplication as WindowedApplication).close();
}
catch(e:Error){}
}
]]>
</fx:Script>
<mx:SWFLoader id="sfwLoader"
width="100%" visible="false"
height="100%"/>
</s:WindowedApplication>

How to convert a string to an object

I'm trying to use a sharedObject to coordinate the movement of several objects on the stage between multiple game players. I think that I'm very close but I seem to be having a problem converting a string stored in the sharedObject into an instance of the Ball class.
My problem is in the soSync function.
I think I need to convert into an object the value of 'objectMoved' that is stored in the sharedObject. I can trace the name of the selected object, but I cannot retrieve it as an object.
How do I store the selected object in a sharedObject and then use it to coordinate motion with the other game players?
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.core.UIComponent;
public var nc:NetConnection;
private var connectionURL:String = "rtmp://server address...";
public var remoteSO:SharedObject;
private var checker:Ball;
public function init():void{
//Create new checkers; place them and create listeners
for (var i:int = 0; i < 3; i++){
checker = new Ball;
checker.x = 150 + (i * 110);
checker.y = 150;
checker.name = String(i);
this.addChild(checker);
checker.addEventListener(MouseEvent.MOUSE_DOWN,handleMouseDown);
}
// Establish connection to the server
nc = new NetConnection();
//Listener triggered by the NetConnection connection
nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
nc.connect(connectionURL);
}
private function netStatusHandler(e:NetStatusEvent):void {
if(e.info.code == "NetConnection.Connect.Success"){
createRemoteSO();
}
}
private function handleMouseDown(e:MouseEvent):void{
//Show which object has been selected
objectInfo.text = "Clicked: "+String(e.currentTarget);
e.currentTarget.startDrag();
e.currentTarget.addEventListener(MouseEvent.MOUSE_MOVE,dragging);
e.currentTarget.addEventListener(MouseEvent.MOUSE_UP,handleMouseUp)
//Update the remote shared object from this client
function dragging(e:MouseEvent):void{
objectInfo.text = "Dragging: "+String(e.currentTarget);
//Set the shared object
remoteSO.setProperty("objectMoved",e.currentTarget.name);
remoteSO.setProperty("x",e.currentTarget.x);
remoteSO.setProperty("y",e.currentTarget.y);
}
function handleMouseUp(e:MouseEvent):void{
e.currentTarget.stopDrag();
objectInfo.text = ""
e.currentTarget.removeEventListener(MouseEvent.MOUSE_MOVE,dragging)
}
}
private function createRemoteSO():void{
// Create reference to the remote shared object
remoteSO = SharedObject.getRemote("remoteSO",nc.uri,false);
remoteSO.connect(nc);
//Listener to handle changes to the remote shared object
remoteSO.addEventListener(SyncEvent.SYNC, soSync);
}
//Called when a change is made to the remote shared object by other clients
private var counter:int;
private function soSync(se:SyncEvent):void {
if(remoteSO.data.objectMoved){
this.getChildByName(remoteSO.data.objectMoved).x = remoteSO.data.x;
this.getChildByName(remoteSO.data.objectMoved).y = remoteSO.data.y;
}else{
trace("Object does not exist")
}
}
]]>
</mx:Script>
<mx:Text x="147" y="51" text="Selected object"/>
<mx:TextArea id="objectInfo" x="237" y="50"/>
</mx:Application>
Ball.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:UIComponent xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.events.FlexEvent;
private function init():void{
var child:Shape = new Shape();
child.graphics.beginFill(0xff0000, .5);
child.graphics.drawCircle(0, 0, 50);
child.graphics.endFill();
this.addChild(child);
}
]]>
</mx:Script>
</mx:UIComponent>
I think you could use getChildByName("String/ObjectName here").
So in your case...
this.getChildByName(remoteSO.data.objectMoved).y = remoteSO.data.y;
Alternatively, could you not just add the physical object itself when using setProperty as opposed to the objects name. Like so...
remoteSO.setProperty("objectMoved",e.currentTarget);
Your Ball object seems to be a DisplayObject, which are unable to be saved in a shared object as a whole. You can, however, instantiate a Ball object, read properties out of the SO and assign them to your ball. The properties in question seem to be x and y, and not objectMoved, as your ball's name will most likely be in line of instance389 which does not spell a thing if you lose the naming context, and even if not, you can only find a child by name if it still exists. So, if you have only one object of type Ball, you assign it the X and Y read from the SO, if not, you should store several balls in your SO, so you will instantiate them later and preserve all of their coordinates.

Flex: Why are TileList images disappearing on drag?

I'm developing a Flex Air (desktop) application that loads images from the local filesystem into a TileList. The user will then be able to drag (copy) these images out of the list onto another control.
I've finally got the images showing up correctly (and not disappearing after scrolling the TileList) but they seem to disappear from the TileList at the start of a drag operation.
I come from a .NET background and am just learning AS3/Flex, so if you see me using any anti-patterns here, feel free to point them out!
Sample code follows (I've tried to make this as minimal as possible).
Test.mxml:
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication 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[
import mx.collections.ArrayCollection;
import mx.events.FlexEvent;
[Bindable]
protected var _pics:ArrayCollection = new ArrayCollection();
protected function picsList_creationCompleteHandler(event:FlexEvent):void
{
const imageFolderPath:String = "c:\\users\\bbrooks\\Pictures";
var imageDir:File = new File(imageFolderPath);
var imageFiles:Array = imageDir.getDirectoryListing();
for each(var imageFile:File in imageFiles)
{
_pics.addItem(new PictureObject(imageFile.nativePath));
}
// give images a chance to load
var timer:Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, onTimerExpired);
timer.start();
}
protected function onTimerExpired(event:TimerEvent):void
{
picsList.dataProvider = _pics;
}
]]>
</fx:Script>
<mx:TileList id="picsList" x="0" y="0" width="100%" height="100%" dragEnabled="true" dragMoveEnabled="false"
creationComplete="picsList_creationCompleteHandler(event)" >
<mx:itemRenderer>
<fx:Component>
<mx:Image width="75" height="75" source="{data.image}" />
</fx:Component>
</mx:itemRenderer>
</mx:TileList>
</s:WindowedApplication>
PictureObject.as:
package
{
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.Event;
import flash.net.URLRequest;
import mx.controls.Image;
[Bindable]
[RemoteClass]
public class PictureObject extends Object
{
protected var _image:Image = null;
public function get image():Image { return _image; }
public function set image(newValue:Image):void { _image = newValue; }
public function PictureObject(path:String)
{
var imageLoader:Loader = new Loader();
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoaded);
imageLoader.load(new URLRequest(path));
}
protected function onImageLoaded(e:Event):void
{
var imageLoader:Loader = LoaderInfo(e.target).loader;
var bmp:Bitmap = Bitmap(imageLoader.content);
_image = new Image();
_image.smoothBitmapContent = true;
_image.source = new Bitmap(bmp.bitmapData);
_image.width = imageLoader.width;
_image.height = imageLoader.height;
}
}
}
I will mostly reply to your secondary question (guessing it will resolve the primary in one fell swoop): as anti-patterns go, this is not a bad example ;)
You are manually loading the images while the Image class has the loading built-in; just give a URL to its source property and it will automatically load it.
You are setting an Image instance as the source of another Image instance; the source property expects URLs or ByteArrays; I'm surprised it doesn't throw an error; the Image class is probably smart enough to extract the source of the other Image instance.
The Timer is redundant. As said, an Image automatically takes care of loading its content.
The s:Image tag isn't wrapped in an ItemRenderer and hence should have no access to a data property: this code shouldn't even compile.
There's no point in having a Bindable property _pics if you don't plan on binding it.
You use the mx TileList. Why not use the more "modern" Spark version? (This doesn't mean the mx class won't work in a Spark application though).
So you have a lot of deleting to do. You can scrap the PictureObject class altogether; remove the Timer code; and just add the URL Strings to the _pics collection. As a plus you could also replace the mx TileList with a Spark List with TileLayout; something like this:
<s:List id="picsList">
<s:layout>
<s:TileLayout />
</s:layout>
<s:itemRenderer>
<fx:Component>
<s:ItemRenderer>
<s:Image source="{data}" />
</s:ItemRenderer>
</fx:Component>
</s:itemRenderer>
</s:List>
The ActionScript part could be reduced to this:
const imageFolderPath:String = "c:\\users\\bbrooks\\Pictures";
var imageDir:File = new File(imageFolderPath);
var imageFiles:Array = imageDir.getDirectoryListing();
picsList.dataProvider = new ArrayCollection(imageFiles);
Thanks RIAstar. Your answer put me on the track to solving the problem. The new sample code appears below.
The original problem seems to have been with the mx:Image control. Not sure why, but using the s:Image control seems to work.
Granted, this could be accomplished without the PictureObject class at all by simply setting the data source to a list of file paths, but I'm using the image data later and I wanted to get it working by supplying the image data to the custom renderer dynamically.
Test.mxml:
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication 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[
import mx.collections.ArrayCollection;
import mx.events.FlexEvent;
import spark.components.Image;
protected var _pics:ArrayCollection = new ArrayCollection();
protected function picsList_creationCompleteHandler(event:FlexEvent):void
{
const imageFolderPath:String = "c:\\users\\bbbrooks\\Pictures";
var imageDir:File = new File(imageFolderPath);
var imageFiles:Array = imageDir.getDirectoryListing();
for each(var imageFile:File in imageFiles)
{
if (imageFile.extension == "jpg")
{
_pics.addItem(new PictureObject(imageFile.nativePath));
}
}
// give images a chance to load
var timer:Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, onTimerExpired);
timer.start();
}
protected function onTimerExpired(event:TimerEvent):void
{
picsList.dataProvider = _pics;
}
]]>
</fx:Script>
<s:List id="picsList" x="0" y="0" width="100%" height="100%"
creationComplete="picsList_creationCompleteHandler(event)"
dragEnabled="true" dragMoveEnabled="false">
<s:layout>
<s:TileLayout />
</s:layout>
<s:itemRenderer>
<fx:Component>
<s:ItemRenderer>
<s:Image id="imageDisplay"
width="75" height="75" source="{data.bmp}" />
</s:ItemRenderer>
</fx:Component>
</s:itemRenderer>
</s:List>
</s:WindowedApplication>
PictureObject.as
package
{
import flash.display.Bitmap;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.Event;
import flash.net.URLRequest;
import mx.controls.Image;
[RemoteClass]
[Bindable]
public class PictureObject extends Object
{
protected var _bmp:Bitmap = null;
public function get bmp():Bitmap { return _bmp; }
public function set bmp(newValue:Bitmap):void { _bmp = newValue; }
public function PictureObject(path:String)
{
var imageLoader:Loader = new Loader();
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoaded);
imageLoader.load(new URLRequest(path));
}
protected function onImageLoaded(e:Event):void
{
var imageLoader:Loader = LoaderInfo(e.target).loader;
// create our own copy of the bits in the Loader
var bmp:Bitmap = Bitmap(imageLoader.content);
_bmp = new Bitmap( Bitmap(imageLoader.content).bitmapData );
}
}
}