Main

Actionscript 3 Archives

June 10, 2007

Cerchi una consulenza su Flex 3, AIR, Livecycle data services e Java per lo sviluppo di RIA ? E' nata Comtaste Consulting

Dopo oltre un decennio di attività da free lance per lo sviluppo e la consulenza su Flash, Flash Media Server e, successivamente, Flex (fin dalla versione 1) e Flash Lite, ho formato e dirigo un team di professionisti che hanno una profonda conoscenza di queste tecnologie ed un solido background in Java, EJB3, Struts, Hibernate, POJO e Spring in ambiente Java Enterprise (J2EE).
Oltre a frequenti attività di supporto ad Adobe in importanti progetti nell’area EMEA (EuropeMiddleEastAfrica), questo team di consulenza e sviluppo è stato ingaggiato più volte da prestigiose aziende worldwide per consulenza in materia di analisi, sviluppo e ottimizzazione di applicazioni in cui gli aspetti gestionali e di sicurezza tipici del mondo enterprise integrano saggiamente l’attenzione alla user experience che è il fulcro dell’approccio RIA (Rich Internet Applications).

Se hai bisogno di assistenza per un'applicazione interna o vuoi rendere un'applicazione eistente più ricca e accattivante, o se hai un'idea che vuoi realizzare utilizzando le più moderne, efficaci ed affidabili tecnologie disponibili sul mercato quello che stai cercando è il mio team! Forniamo consulenza e assistenza in ogni parte del mondo, on site e off site, both on a Time&Material and on a TurnKey basis.

Per contattarmi in merito ad attività di consulenza, scrivi una email a consulting[ AT ]comtaste.com

June 14, 2007

Adobe AIR, Flex 3 and Integration between Fireworks,Photoshop and Flash CS3 with Flex. All of these topics at the AdobeLive 2007

Today is the second day of AdobeLiveConference here in Italy.
I'm here with Enrique (and some enormous mosquitos) in the business room of the AdobeLive and we're about to start our presentation.

Enrique will present Adobe AIR (formerly Apollo) and talk about Flex 3 and new features.

After his presentantion I'll show the integration of the Adobe CS3 with Flex and Flex Builder.
It's incredible how many things designers and creative are now able to do to help Flex developersin creating the user interface of Flex applications.
Using Photoshop CS3, Fireworks CS, Illustrator CS3 and Flash CS3 , of course, they can export graphic symbols, layouts and components for the Flex enviroment.

With Fireworks CS3 you can now use the Exoprt as MXML features to convert a PNG layouts into MXML code. You can do this using the new Flex Component Common Library (you can also create your own Flex components using an image and a javascript JSF file).
The MXML code generated from Fireworks is ready to be edited and customized by the developer in Flex Builder.

With Illustrator CS3 you can create vector based symbols and export them as SWF files, ready to be used and imported in Flex. For example you can export your vector symbols and then use them for change the style of a button flex component usign :

overSkin: Embed(source='styles.swf', symbol='mysymbol');
upSkin: Embed(source='styles.swf', symbol='mysymbol');
downSkin: Embed(source='styles.swf', symbol='mysymbol');

Then in Flash CS3 you can do whatever you want with the Flash CS3 Component Kit for Flex. You can interact in Flex with Flash contents, call public methods, refer to each single object.

If you're in Milan come to see the sessions !
They're great !

June 18, 2007

Form fields focus and keyboard events in Flex 3 form based applications

We're working on some projects in Flex where the use of the keyboard to navigate through the application is a key aspect.
They're both Flex 2 form based application

Our goals were :
- at the start up of the application give the focus to the first form field
- pressing the tab key cycling the focus through all the form fields

Although it seams like very simple, the focus in Flex 2 is not so easy.
We had strange behaviour that mostly depend on how the Internet Explorer uses the ActiveX contents :
- although when the application has been loaded the foucs was on the first field, pressing the tab key once, the focus goes outside the Flash Player applet to the browser controls

To solve the problem of the fucus lost by the Flash Player you can use this small workaround :

keyFocusChange="event.preventDefault();focusManager.getNextFocusManagerComponent(event.shiftKey).setFocus()"

The keyFocusChange is on the Application tag.

In order to make the focus in Flex 2 works for Internet Explorer, it's not enough to set it up using Javascript when the page loads.
Internet Explorer does not give you the ability to an ActiveX content to get the focus.
So for example in a Flex 2 application that has 3 text inputs when the last one has the focus and you click on the tab, the focus quits from the Flash Player 9 ActiveX and goes to the HTML page content.

That's a bad behavior for your application.

To overcome this problem we have to intercept the key pressed by the user and disable the default action of the browser to prevent the browser handling of the key.

Continue reading "Form fields focus and keyboard events in Flex 3 form based applications" »

June 21, 2007

Using Cairngorm 2 in Enterprise RIA development: when and why use (or not) it

What is Cairngorm?
Cairngorm 2 is a lightweight framework for Enterprise RIA development in Flex 2; Cairngorm encourages the use of the best development practices on developer's side.
It takes advantage of well know Java and J2EE design patterns such as the Model View Controller, the Service Locator, the Model Locator and the View Helper.
The architecture is totally free and you can download the latest version (Cairngorm 2.2, at the moment of writing) from Adobe Labs:
http://labs.adobe.com/wiki/index.php/Cairngorm#Downloads

Why to use Cairngorm 2 in Flex development ?

Cairngorm is made up of only few Actionscript 3 classes, but in order to start implement it fast in enterprise project, you have to spend some time on it. For me this time just last a few days, spent in developing two small Flex applications.
Once you reach the top of the Cairngorm's small learning curve, you will have a complete view of the framework's functionalities and Flex as well, and the development time of enterprise application will be faster.
One of the benefits in using Cairgorm 2 is that it helps to concentrate on the application business logic.
The use of universally recognized design patterns in the enterprise application field helps enormously the insertion of new software developers into an already started project. The main reason of that is that they will have already a clear idea of the data flow because of the use of a standard and rigid architecture, very similar to Java and J2EE ones(I mean the use of Service Locator, Model Locator and the View Helper i.e.).

Moreover thanks to a coding activity that follows specific rules, the debugging phase of the application will become remarkably faster.
With the use of Cairngorm my mental approach to Flex application planning is changed, now starting from the use cases I'm able to have an idea of the final structure.

Why not to use it?

As I already said, the use of Cairngorm offers remarkable advantages, but someone seems to consider it the silver bullet of Flex development. You have to evaluate if you effectively need your application to be based on Cairngorm and not using it only to be fashionable
Steven Webster himself, tha author of Cairngorm, wrote an interesting post in his blog titles: “Why I think you shouldn’t use Cairngorm”, with a checklist to evaluate before using it: http://weblogs.macromedia.com/swebster/archives/2006/08/why_i_think_you.cfm

On my personal experience I can say that the determining elements for using or not Cairngorm should be:
use case number,
developers number,
a plan to introduce or not new developers to the project
future implementation of new features
scalability, mantainability and reuse of the code written across different projects

Documentation and other resources
There is a community driven site with the scope of collecting Cairngorm documentation: http://www.cairngormdocs.org/
The six parts article from Steven Wester is interesting too:
http://www.adobe.com/devnet/flex/articles/cairngorm_pt1_04.html
Cairngen is an automatic Cairngorm code generator, I never used it so I cannot judge, but I think it is worth a try:
http://www.ericfeminella.com/blog/cairngen/

In the next posts about Cairngorm I'll go deep in the code and illustrate the use of Cairngorm in specific situations.

August 7, 2007

Creating an ObjectManager for improving the Flex interaction with Ajax or Javascript - 2nd part

In my previous post I have illustrated the creation of a simple object manager to make a javascript application correctly dialog with a Flex movie. That is a simple and well functioning solution, however it is not suitable for a more complex context, when it is necessary, for instance, to use several Flex or Javascript/Ajax applications.

What is the right choice in such a situation? The solution often depends more on the developer's creativity than on the possibilities offered by the technology in use.

Let's think, for example, to a comparable situation in actual life: one or more people try to contact the same person that is not available at that moment. If the communication were not much important, each of them could simply try later on, with the hope to find the person available (previous solution), although in the meantime others might anticipate his/her call. What if the communication were extremely important, and risks to arrive too late (after our competitors' communication, for instance)? In order to avoid that possibility and all the related consequences, a voice mail (or a simple answering machine) could be used, as well as, at a later stage, a personal secretary could be hired. The messages will be recorded in their incoming order (for example using a queue or a single instance if we need only the last message), and as soon as the address is available again he/she will listen to the recorded messages or will be informed about them by his/her secretary. We shall now examine how to implement the easiest case, taking again as an example the disabilitation of the Flex application:

- We create a JS class named ObjectManager, it will represent our answering machine. We also create an empty constructor, in this case we shall not use status variables related to the Manager:

ObjectManager = function () {

}

If necessary we could insert variables such as this.available into the object in order to indicate its availability or to initialize global variables.

The only method which is necessary for the object manager's functioning is AddObject. With this function we'll have the possibility to add the desired object (e.g. a Flex movie) to the manager class:

ObjectManager.prototype.AddObject = function (objectName) {

                if(eval('this.' + objectName +' == null')) {

                               eval('this.' + objectName + ' = new Object()');

                               eval('this.' + objectName + '.setStatus = null');

                               eval('this.' + objectName + '.enabled = 1'); //Default status value

                               return true;

                }

                else

                               return false; //object already registered

}

In this way, in the object manager will be created a simple object that we shall use to keep all the information which are necessary to guarantee the proper functioning of the application. Every object created in the object manager is directly linked to the object we want to control through the use of a unique string which represents it. For this reason it is necessary to use the function eval(string), as in the object manager we will not have direct reference to the objects to control.

September 1, 2007

Introducing VEGAS, an Actionscript 3 / 2 and SSAS framework - Global event-listeners and addEventListener for ALL events

Vegas is an OpenSource Framework based on ECMASCript that can be used both on Actionscript 3, Actionscript 2, and Server Side Actionscript and it provides a lot of cool feature to help developers creating RIAs.

The main core features of VEGAS are:

  • AS3, SSAS and AS2 Framework.
  • Unit Test based on ASTUce.
  • AS2 librairie is “MTASC compatible” !
  • Ready to use EDEN.
  • SSAS library based on Core2 and EDEN.
  • ADT (Abstract Data Type) package in AS2, AS3 ans SSAS libraries (queue, map, collections, stack, bag, iterator, ... polymorphism with JAVA Collections)
  • Events package : Event’s model based on W3C Dom2 with bubbling, capturing etc + FrontController pattern.
  • String tools : JSON, Eden serialization/deserialization, Lunh, wildcard, StringFormat...
  • Tools : Serializer, Copier, ArrayUtil, etc..
  • Logging model to use SOS console, LuminicBox FlashInspector, XPanel... AS2 logging model use polymorphism with mx.logging package in AS3 framework.
  • Pattern MVC : 3 implementations with a FrontController or IView, IModel and IController or IObservable/IObserver implementation.
  • Pattern Visitor interfaces (IVisitor, IVisitable).
  • Factory tools (DisplayObjectFactory, ContextMenuItemFactory...)

With Vegas you can use 3 other libraries based on Vegas : PEGAS, ASGard, Lunas. This 3 libraries are in the SVN of VEGAS.

PEGAS

  • Color Manipulation.
  • draw API tools (ArcPen, BezierPen, RectanglePen, Canvas....)
  • Transitions package (Tween, ..)
  • geom package with flash.geom polymorphism for FP7 & FP8 and other tool class (Vertex, Vector2, Vector3, Quaternion...)
  • Maths tools (Prime, Factor, Range...)
  • Process package (Sequencer & Action).
  • UI package. (KeyValidator, DoubleClick...)

ASGard

AS2 version :

  • AS3 Framework polymorphism.
  • Display package (Bitmap, DisplayObject, DisplayLoader, FlashPaperLoader, VideoDisplay, ZoomDisplay...)
  • Loader package (URLLoader, JSONLoader, EdenLoader, StyleSheetLoader...)
  • Remoting package with no Macromedia Framework’s dependencies.
  • Localization and system package
  • Configuration model.
  • Text Package (StyleSheet, ...) like AS3 flash.text framework.

In the SSAS(Server Side ActionScript) version for Flash Media Server :

  • The same Remoting class like AS2 and AS3 libraries.
  • asgard.server.Application class to creates your FMS application based on VEGAS.
  • asgard.server.Gateway class to creates a Gateway based on the FrontController of Vegas (used AS2 Event in the client application and send this events with the NetConnection.call method directly in the server side FrontController.

LunAS

This library based on ASGard and VEGAS to create components. It's not a component of framework but a framework to make components !!

Use examples in AS2/bin/test/lunas to test this framework.

  • bar package : Progressbar, scrollbar...
  • button package
  • container package : SimpleContainer, ListContainer, ScrollContainer, AutoScrollContainer, MatrixContainer...
  • cell package : cells in list and datagrids
  • list package : List components based on containers and with a polymophism with mx package of macromedia.
  • shape package : all shape components.
  • stepper package : basic implementation to create Stepper components.
  • text package : Label, TextArea and TextInput abstract implementation.

Global event-listeners

In some rare cases (especially for debugging purposes) it might be useful to add an event listener that catches all events that are thrown in your application.

In order to achive this, you do not need to register the event listener separately for each event that might be triggered, but use the addGlobalEventListener() instead :

import vegas.events.EventDispatcher ; import vegas.events.EventListener ;

import test.events.DebugHandler ;

var disp:EventDispatcher = new EventDispatcher() ;

var global:EventListener = new DebugHandler("global") ;

// register the global event listener.
disp.addGlobalEventListener( global ) ;

disp.dispatchEvent( "onLogin" ) ;
disp.dispatchEvent( "onLogout" ) ;


// unregister the global event listener.
disp.removeGlobalEventListener(global) ;

disp.dispatchEvent( "onLogin" ) ;
disp.dispatchEvent( "onLogout" ) ;

This event listener will now be called for both events, the onLogin and the onLogout event.

However, you should be aware, that global event listeners are processed after all local event listeners handled the event.

The removeGlobalEventListener() method unregister the global event listener.

In VEGAS you can apply a global event listener with the method addEventListener and the magic type : "ALL"

import vegas.events.EventDispatcher ; import vegas.events.EventListener ;

import test.events.DebugHandler ;

var disp:EventDispatcher = new EventDispatcher() ;

var global:EventListener = new DebugHandler() ;

// register the global event listener.
disp.addEventListener( "ALL", global ) ;

disp.dispatchEvent( "onLogin" ) ;
disp.dispatchEvent( "onLogout" ) ;


// unregister the global event listener.
disp.removeEventListener( "ALL", global ) ;

disp.dispatchEvent( "onLogin" ) ;
disp.dispatchEvent( "onLogout" ) ;

NB : In this examples, the DebugHandler class is an easy EventListener implementation.

import vegas.events.Event ; import vegas.events.EventListener;

/**
* The DebugHandler class.
*/
class test.events.DebugHandler implements EventListener
{

/**
* Creates a new DebugHandler instance.
*/
public function DebugHandler(){}

/**
* Handles the event.
*/
public function handleEvent(e:Event)
{
trace( this + " handled event : " + e.getType() ) ;
}

/**
* Returns the String representation of the object.
* @return the String representation of the object.
*/
public function toString():String
{
return "[DebugHandler]" ;
}

/**
* The internal private name property of this instance.
*/
private var _name:String ;

}


Conclusion

Vegas actually implements a lot of features that any other fameworks actually implement in actionscript. It's inspired by great architectures like J2EE, Apple notification center for the EventDispatcher and introduces the ForntController Pattern and Pattern Visitor interfaces. In this post you can see the "General event listener", the method to listen for all event in an application, this is only a little part of the Event Model introduced by Vegas. I think that the Event model it's the most important feature of the framework. In the next post, I will show you the other's important method and the implementation of some pattern.

September 28, 2007

Automating ActionScript 3 classes generation from Java Beans in a LiveCycle Data Services context

In a Flex application that uses LiveCycle Data Services or the previous Flex Data Services to manage data from a remote server there is the requirement that Flex domain model classes have to match Java domain model, in structure, properties and types. Usually it means that for each Java class that is supposed to be configured as a remote alias one should write down an ActionScript class with the same properties, just as described in the Adobe livedocs at Livedocs
The documentation provides a mapping for ActionScript data types and Java data types and specifies that Java classes are dealt with through the Java Beans specification, that can be downloaded here: Javabeans

The Java class is serialized and all of its public properties and the ones with getter and setter methods are serialized. All other properties are not, including the ones without a getter. There is one thing related to the Java beans that worths a bit of attention, and it is bean attribute names that start with a lower case character followed by a upper case character: their getter and setter methods will have get/set followed by at least two upper case characters, for example "aFoo" will have "getAFoo" and "setAFoo". When the Java introspection mechanism, described in the above specification, finds these kind of properties, it will infer that the property is called "AFoo". That implies that inside the ActionScript class that matches the Java bean the property has to be called "AFoo", otherwise it will not be recognized. This usually translates on the flash log in a "ReferenceError: Error #1056: Cannot create property AFoo on [...]".

Consider the case where all of the properties of a class are declared in Java with a lower case followed by an upper case, one could easily convert into an ActionScript class that follows the same naming convention and, at runtime, there will be an empty object, with the right type but no contents; the ReferenceErrors in the flashlog will point out the problem and the solution, in this case, is to call ActionScript properties starting with two upper case characters: "AFoo".

Iin an enterprise application there can be many Java bean classes to be converted to ActionScript counterparts, a simpler way of solving this and possibly other problems related to Java to ActionScript conversion would be the use of an automatic tool. At the time of writing this blog post I personally did not find a tool that performs the conversion, a tool that can be easily integrated into an IDE, like Eclipse, or used as an Ant task, thus I'm considering writing one myself. The backend of this tool would use java.beans.Introspector to get the java.beans.PropertyDescriptor for each property of the bean, map the Java types to the ActionScript ones and generate the required imports. I'll keep the blog updated with progress on the tool, as well as interesting parts of the source code.

October 27, 2007

Techniques to clone an ActionScript 3 Object in Flex using AMF3

If you want to clone an Actionscript Object you have three possible ways: the deep-copy, the shallow-copy and the lazy-copy.

The deep-copy is the slowest but the most effective way, because the new object will lose any reference to the original object, so there will not be any data shared between the objects.


The shallow-copy results in a situation in which some data are shared between the objects, with the advantage that their execution is faster.

The lazy copy is a combination of both the above techniques. When initially copying an object, a (fast) shallow copy is used. A counter is also used to track how many objects share the data. When the program wants to modify an object, it can determine if data are shared (by examining the counter) and can do a deep copy if necessary.

The Flex API has a function that is called ObjectUtil.copy; it is a nice function but the bad thing is that you cannot work on all the object classes. You can only make your own function for deep copy, and to do that you need to know everything about its structure.

Here it is how Flex copies objects:

var buffer:ByteArray = new ByteArray();
buffer.writeObject(value);
buffer.position = 0;
var result:Object = buffer.readObject();
return result;

It works good, right?. Here is what it does: instead of introspection and recursively copying properties from one object to another it will serialize the object as an array of bytes and then wil de-serialize it.

If you use the AMF3 there can be some strange things going on: the failure may be caused by casting back to the original object class, and the [Transient] metadata tag can affect the output.

When the object will be de-serialized it will not be possible to creat it as an istant of a class (even if it has all its properties). If you want to have this you can inform AMF3 about the object class. There are 2 ways to do that:

use [RemoteClass] metadata
use registerClassAlias()

Even though the first way is better and nicer it may not work in all cases because the remote class information is stripped from the byte array in some cases.

Here is how to use the registerclass alias:

// TestClass doesn't have [RemoteClass] metadata or
// it does not work, so we need to make an association between
// the TestClass and the full qualified name (com.tests.TestClass)
registerClassAlias("com.tests.TestClass",TestClass);

// The result of the copy can be casted now without errors
var testCopy:TestClass = TestClass(ObjectUtil.copy(test));

Now, this is a very effective method but it has one flaw: it is not compatible with bitmapdata. Here is a workaround for this issue:

public function copyBitmap(target: DisplayObject) : Bitmap
{
// Create the bitmap data object with the right size.
var data : BitmapData = new BitmapData(target.width, target.height, true, 0);
// Draw the target object into the bitmap data.
data.draw(target);
// Create a new bitmap object associated with this data.
var bitmap: Bitmap = new Bitmap(data);
return bitmap;
}

Some interesting links where you can go deeper :
Object copy
ObectUtil.copy() Flex API reference

May 12, 2008

Improve the ObjectHandles library with a smoother resizing movement

A very common UI element found in many applications are those little square handles around an on-screen object that allow you to move & resize it. To do this you can use the great ObjectHandles library.

ObjectHandles (http://osflash.org/projects/objecthandles) is a library to allow a user to move and resize UI elements in a Flex based application.
It provides drag handles around controls that users can manipulate with their mouse. Any Flex component can be placed within an ObjectHandles container to quickly allow you to add functionality.

It behaves as a container object where you can put any other flex components and use its resizeable functionalities.

Features of the ObjectHandles library:

* Move & Resize Functionality for any flex component
* Ability to limit movement and/or resizing in both vertical and horizontal directions
* Ability to limit movement and/or resizing along an anchor
* Simple 1-file (.swc) install
* Mouse cursors change when over different handles
* Graphical handle support
* Aspect ratio support
* Initial rotatation support has been added

ObjectHandles is a very cool library for your project when you want to implement moving & resizing any kind of flex object.

Example usage:

In the example below you'll see two buttons in a vbox that can be moved together. This is the mxml to achieve that:

<oh:ObjectHandles x="10" y="158" width="107" height="108"
minHeight="30" minWidth="30">
<mx:VBox borderStyle="none" top="0" left="0" right="0" bottom="0">
<mx:Button width="100%" height="50%" />
<mx:Button width="100%" height="50%" />
</mx:VBox>
</oh:ObjectHandles>

Or if you want an Actionscript example:

Here's an example to dynamically load an image into an ObjectHandle and allow resize movements:

protected function init() : void
{
var oh:ObjectHandles = new ObjectHandles();
oh.height = 50;
oh.width = 50;

var image:Image = new Image();
image.source = "snowflake.png";
image.percentHeight = 100;
image.percentWidth = 100;
image.maintainAspectRatio = false;

oh.addChild(image);
oh.allowRotate = false;

genericExamples.addChild(oh); // replace genericExamples with a canvas in your application
}

Improving the experience of the ObjectHandles library

When you drag or resize an object from right to left or from up to down everything works great.

But if you to resize the object back (from right to left) you'll see that the inside object will cause a strange flickering.

To prevent this we can use the "Flex Move Effect" and "Flex Resize Effect" instide of change programmaticaly width and height and x and y.

How it actually works:

Inside the ObjectHandles.as Actionscript 3 class, you can find the protected function onMouseMove(event:MouseEvent) : void.
This is the function that moves and resizes UI elements in a Flex based application. Find the following line inside the ObjectHandles.as:

if( wasMoved || wasResized )
{
applyConstraints(desiredPos,desiredSize);
x = desiredPos.x;
y = desiredPos.y
width = desiredSize.x;
height = desiredSize.y;
}

The applyConstraints() method simply applies restrictions to your objects like xAnchor, minium size, etc. The other four lines simply set the x,y coordinates and the width and height properties of the Flex object.

Now let's change this four lines to prevent the strange flicker bug that affects the object :

if( wasMoved || wasResized )
{
applyConstraints(desiredPos,desiredSize);

if(moveEffect.isPlaying){
moveEffect.end();
}
moveEffect = new Move();
moveEffect.target = this;
moveEffect.duration = 1;
moveEffect.xTo = desiredPos.x;
moveEffect.yTo = desiredPos.y;
moveEffect.play();

if(resizeEffect.isPlaying){
resizeEffect.end();
}
resizeEffect = new Resize();
resizeEffect.target = this;
resizeEffect.duration = 1;
resizeEffect.heightTo = desiredSize.y;
resizeEffect.widthTo = desiredSize.x;
resizeEffect.play();
}

It replaces the brutal property changing of the widget with a smoothness move and resize effect provided by Flex.

In the next post we will see how to create a snap to grid and a snap to line effect.

Conclusion and references:


ObjectHandles google code home
Class Move
Class Resize

May 26, 2008

Google Maps API for Flex and Flash: some tips and notes

Finally the official version of Google Maps for Flash is arrived.
Google has just released the Actionscript API that provides map functionalities to web applications in a way really similar to the Javascript version.
You can follow the instructions in the Setup or Tutorial pages on Google Code to easily build your web map application.
Here is a sample application based on data from Yubuk (click on the image):
GoogleMapsFlex

And now some hints that can be useful when creating your first Flex application with Google Maps:

1) Remember to add the .swc library provided by Google in their SDK in your compiler options. If you are using Flex Builder you can do that simply going in the project properties, under Flex Build Path, then Library Path and click Add SWC. Otherwise, if you like to use the command line, you can use the -library-path command as explained in the Google tutorial.

2) Pay attention to the events: you can't use the standard Flex events but you need that ones provided by the Google SDK, such as MapMouseEvent.CLICK.

3) Custom markers have a bug in the version 1.3. To avoid this bug there's a workaround in Google Code. The example has a small error in the marker event listener, the event should be MapMouseEvent.CLICK (as explained above).

I think that Google made a great work porting their Google Maps API to Flash. It is still incomplete but it's already possible to see the huge potential provided by the cooperation between Google Maps and Flex. I'm sure that in the near future there will be many interesting RIA based on these technologies.

July 8, 2008

Using the Loader class to load and set dimensions of an image from the remote server in Flex 3

Working and creating images in Flex could not be as easy as it looks. When you load an image loaded from the remote server you will tipicaly receive a ByteArray data. The ByteArray image doesn't contain any information such as the width and height of that data. Moreover you must know when the entire bytearray it's been fully loaded on the client.

To do this we need to load the bytearray with the Loader Class.
So we need to extend an mx.control.Image Class and add the loader information:

private var _loader:Loader = new Loader();

Now wee need to implement a method to load the bytes:

public function loadBytes(bytes:ByteArray, context:LoaderContext = null):void
{
_loader.loadBytes(bytes, context);
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onBytesLoaded);
}

This method will load the byte array image and add the listener to know when is ready.

After the event.complete handler will bring up with the loader information:

private function onBytesLoaded( e:Event ):void
{
source = _loader.content;
width = _loader.contentLoaderInfo.width;
height = _loader.contentLoaderInfo.height;
removeChild(_loader);
}

You can see that now we can set the source for the image and than set the correct width and height getting the information from the _loader.contentLoaderInfo.

Finally we remove the loader.
Here you can find the complete source for the ByteArrayImage Class:

The Class

package
{
import flash.display.Loader;
import flash.events.Event;
import flash.system.LoaderContext;
import flash.utils.ByteArray;

import mx.controls.Image;

public class ByteArrayImage extends mx.controls.Image
{
private var _loader:Loader = new Loader();

public function ByteArrayImage()
{
}

override protected function createChildren():void
{
_loader.visible = false;
addChild(_loader);
}

public function loadBytes(bytes:ByteArray, context:LoaderContext = null):void
{
_loader.loadBytes(bytes, context);
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onBytesLoaded);
}

private function onBytesLoaded( e:Event ):void
{
source = _loader.content;
width = _loader.contentLoaderInfo.width;
height = _loader.contentLoaderInfo.height;
removeChild(_loader);
}
}
}

A simple implementation:

import flash.image.JPEG;
import flash.image.PNG32;
myJPG:ByteArray = new JPEG( bitmapData , 300, 300, 80 );
myPNG:ByteArray = new PNG32( bitmapData , 1500, 1260 );

myByteImage:ByteArrayImage = new ByteArrayImage();
myByteImage.loadBytes( myJPG or myPNG );

Reference:
ByteArray LiveDocs
Loader LiveDocs

About Actionscript 3

This page contains an archive of all entries posted to Comtaste Consulting | Enterprise RIA consulting and development in the Actionscript 3 category. They are listed from oldest to newest.

AIR Adobe Integrated Runtime is the next category.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.33