Archive Page 2

17
Jun

Loading FXG graphic at runtime

Yesterday I posted a blog post about the fact that FXG code can increases your SWF container size and tax your CPU, so you should take that into account when deciding if it’s better to load images on runtime, embed assets or use FXG code. Adding optimized FXG or MXML Graphics (MXMLG) is the same in term of fact that the code you add will increase the application’s swf size so although it wont tax your CPU unless you add the child to the display object it will still increase your container size just like embedding assets.

There are many times when you do want to use FXG code. For instance you don’t want to degrade the designer’s graphic, or you want to keep the vector to scale high quality, change properties on runtime, etc. You still want to avoid increasing your container size.

There is a way. You can use the FXGStringConverter I created few months ago and load the FXG on runtime, just as you with images and other assets.

Take a look at a simple class that allow you to load the FXG and use it in your application:


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

	<fx:Script>
		<![CDATA[

			import com.elad.framework.utils.fxgconverter.FXGStringConverter;

			[Bindable]
			public var xLocation:int = 0;

			[Bindable]
			public var yLocation:int = 0;

			private var _source:String;

			public function get source():String
			{
				return _source;
			}

			public function set source(value:String):void
			{
				_source = value;

				loadFxg();
			}

			private function loadFxg():void
			{
				var loader:URLLoader = new URLLoader();

				loader.addEventListener( Event.COMPLETE, onLoaded );
				loader.addEventListener( IOErrorEvent.IO_ERROR, onError );
				loader.load(new URLRequest(source));
			}

			private function onLoaded(event:Event):void
			{
				var fxgString:String = event.target.data;

				var group:Group = FXGStringConverter.convertFXGStringToComponent( fxgString, true );
				fxgHolder.addElement( group );
			}		

			private function onError(event:IOErrorEvent):void
			{
				trace( event.text );
			}

		]]>
	</fx:Script>

	<s:Group id="fxgHolder" x="{xLocation}" y="{yLocation}" />

</s:Group>

Here’s an example where I am loading the FXG code on runtime and add it as a new element to the display object:


<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
			   xmlns:s="library://ns.adobe.com/flex/spark"
			   minWidth="955" minHeight="600"
			   xmlns:local="*" xmlns:utils="utils.*">

	<utils:Fxg id="fxg" source="icon.fxg"
			   xLocation="100" yLocation="100" />

</s:Application>

I am using an FXG code from Adobe’s tutorials:


      <s:Group x="0" y="0">
          <s:Rect x="0.5" y="0.5" width="100" height="30">
            <s:fill>
              <s:LinearGradient x="0.5" y="15.5" scaleX="100" rotation="-0">
                <s:GradientEntry color="#ffffff" ratio="0"/>
                <s:GradientEntry ratio="1"/>
              </s:LinearGradient>
            </s:fill>
            <s:stroke>
              <s:SolidColorStroke
                color="#0000ff"
                caps="none"
                weight="1"
                joints="miter"
                miterLimit="4"/>
            </s:stroke>
          </s:Rect>
      </s:Group>

Result:

screen-shot-2010-06-17-at-82558-am

16
Jun

FXG code increases your swf container’s size and tax your CPU

I am a big fan of FXG but I want to point out a caveat in regards to using FXG code in your Flash/Flex applications. FXG code increases your SWF container size and tax your CPU, so you should take that into account when deciding if it’s better to load images on runtime, embed assets or use FXG code.

In one of the applications that I am developing I took out only one FXG class and was able to reduce the size of my application from 1.9MB bytes to 1.6MB, see below:

With the FXG class:

screen-shot-2010-06-16-at-15903-pm

Without the FXG class:

screen-shot-2010-06-16-at-15801-pm

Now take a look at the profiler when using an application that is using the FXG code and without. It peaked from
1476K to 8594K.

With the FXG code:
screen-shot-2010-06-16-at-21643-pm

Without FXG code:
screen-shot-2010-06-16-at-21747-pm1

Keep in mind that the FXG code is consuming 7,633 lines of code so it’s an extreme case, but you may have cases where many FXG classes together can make that much of code.

Comparison of optimized FXG vs PNG

Added Wed June 23, 2010:
I want to point out that in the previous example I have used MXML Grahpic (AKA: MXMLG). Take a look at the same vector art exported into FXG from illustrator placed in the application as a .fxg file and imported into the application, see below:


<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" xmlns:local="*">

	<local:wtb_avatar />

</s:Application>

The application is compiling the FXG into SWF primitives and is better optimized. Using the FXG file I have increased my memory used from 1483K to 1881K, see below:

screen-shot-2010-06-23-at-110024-am

screen-shot-2010-06-23-at-110108-am

At the same I have increased the size of the SWF container from 71Kb to 228Kb so the FXG code still added as an embedded asset and increased the application’s size significantly.

screen-shot-2010-06-23-at-110152-am

screen-shot-2010-06-23-at-110222-am

For the sake of argument, I have used an png file that looks exactly as the fxg art and the png file came out to be 66Kb.

Now I am embedding the asset into my application:


<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" xmlns:local="*">

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

</s:Application>

When I run the application the memory usage climbed to 2423K, which is more than the FXG, which was1881K. The SWF container size was smaller and turned to be 152Kb instead of 228Kb when I used FXG. So the optimized FXG gave me better performance but increased my SWF container. See screenshots below:

screen-shot-2010-06-23-at-122528-pm

screen-shot-2010-06-23-at-123712-pm

The conclusion is that every case need to be examined on a case to case basis. You can than decide what’s the best approach; using FXG, MXMLG, embed images, load images during runtime or load FXG during runtime (as I showed here). It is a matter of what you’re trying to achieve?

You should answer these questions which can help you decide:

  • Do you need to change properties or scale during runtime?
  • How many lines of code is your FXG file?
  • Do you need your graphic to be embedded or loaded at runtime?
  • How important is the quality of your graphic and do you care if the quality of the art will degrade?

Cheers :)

21
May

Format TLF to accept HTML tags

After struggling with TLF today trying to format different HTML tags. There are all kind of great experiments out there such as TLFX, which try to address some of these concerns. However, since the project is still in the works I rather not use it on production code.

I end up using what’s available in TLF, which is still very limited. It appears that TLF doesn’t support many of the common HTML tags you exact such as “b” or “font tags” at the same time it does support some HTML tags (see list here) and what works is using the span property and attaching attributes.

There are two tequinques I found.

You can use the TextConverter util to import and export HTML, see example below:


<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" minWidth="955" minHeight="600"
			   initialize="init()">
	<fx:Script>
		<![CDATA[
			import flashx.textLayout.conversion.TextConverter;
			import flashx.textLayout.elements.TextFlow;

			public function init():void
			{
				var markup:String = "<TextFlow xmlns='http://ns.adobe.com/textLayout/2008'><p>hello Flex<span fontWeight='bold' color='#cccccc' fontSize='28' fontFamily='Neutraface Text Demi'>Flash</span> Hello ActioinScript.<span fontSize='42'>Hello TLF</span></p></TextFlow>";
				var textFlow:TextFlow = TextConverter.importToFlow(markup, TextConverter.TEXT_LAYOUT_FORMAT);

				descriptionRichText.textFlow = textFlow;
			}

		]]>
	</fx:Script>

	<s:RichText id="descriptionRichText" blendMode="normal"
				color="#000000" fontFamily="Arial"
				whiteSpaceCollapse="preserve" x="350" y="102"/>

</s:Application>

This technique works well but require you to add the following tag:


<TextFlow xmlns='http://ns.adobe.com/textLayout/2008' />

Additionally you can use TextFlowUtil, see below:


<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"
			   minWidth="955" minHeight="600">

	<fx:Style source="Main.css"/>

	<fx:Script>
		<![CDATA[
			import mx.controls.Alert;

			import spark.utils.TextFlowUtil;

			protected function button1_clickHandler(event:MouseEvent):void
			{
				try {
					descriptionRichText.textFlow = TextFlowUtil.importFromString(textArea.text );
				}
				catch (error:Error)
				{
					Alert.show("HTML error: " + error.message);
				}
			}

		]]>
	</fx:Script>

	<s:TextArea id="textArea" x="102" y="75"/>
	<s:Button x="102" y="244" label="Submit HTML" click="button1_clickHandler(event)"/>

	<s:RichText id="descriptionRichText"blendMode="normal"
				color="#000000" fontFamily="Arial"
				whiteSpaceCollapse="preserve" x="350" y="102"/>

</s:Application>

screen-shot-2010-05-21-at-83336-pm

Using the following HTML code produced a successful format.


<p>hello Flex<span fontWeight="bold" color="#cccccc" fontSize="28" fontFamily="Neutraface Text Demi">Flash</span> Hello ActioinScript.<span fontSize="42">Hello TLF</span></p>

Notice that I also embedded an external font: “Neutraface Text Demi”.


@font-face
{
	fontFamily: "Neutraface Text Demi";
	src: url("assets/fonts/NeutraText-Demi.otf");
	embedAsCFF: true;
}

Hopefully you’ll find this post helpful.

24
Apr

Apple has always been a closed ecosystem - so why are we surprised?

In 1984 Apple spent $900,000 on a commercial during the Super Bowl, and Apple introduced the Apple Macintosh for the first time. It is regarded as a masterpiece in advertising and one of the most successful commercials of all time.

In his 1983 Apple keynote address, Steve Jobs made the following comment before playing the commercial for the first time:

“It is now 1984. It appears IBM wants it all. Apple is perceived to be the only hope to offer IBM a run for its money. Dealers, initially welcoming IBM with open arms, now fear an IBM-dominated and -controlled future. They are increasingly turning back to Apple as the only force that can ensure their future freedom. IBM wants it all and is aiming its guns on its last obstacle to industry control: Apple. Will Big Blue dominate the entire computer industry?”.

screen-shot-2010-04-24-at-73338-am

Ironically, three decades later Steve Jobs is still chasing the Big Blue box, in the past Big Blue was IBM’s nickname and today it’s the blue lego plugin for Adobe.

176

What Steve Jobs was talking about in the 1984 ad was the first IBM PC, which was created using off the shelf parts for the first time and marketed by outside distributors. It was introduced in 1980, and soon after the IBM clones began to pop out everywhere. Due to the use of the same operation system (dos) and low price, the eco-system allowed developers to deploy the same software on different machines. Jobs and his executives decided not to license Apple’s technology or OS to any other company. Back then Apple wanted total control. It wanted to sell all the products that are related to their computers; they wanted no competitors.

So what was the Super Bowl ad all about? That was just a marketing masterpiece, but in reality Apple was always a closed ecosystem. iTune lock your music. WebKit Open source open standards, but allow them to take control. Mac OS was never licensed. iHTML, iPad, and the removal of applications are no different. I would go as far as to say that Apple would want to restrict the entire web if they could, and today with OS X accountimg for nearly 11% of web usage that can be a reality!

Apple always protected their margins by keeping prices too high and controlling the end user. The control was from hardware to software. We all know how expensive it is to purchase any piece of hardware for the Mac in comparison to a PC. The majority of Apple users benefit from the ease of using a closed ecosystem. Since Apple controls the entire cycle from software to hardware, the experience is superior, and the average Joe Schmoe doesn’t really care about Flash, Unity3D, or even if Apple will block Photoshop from OS X 10.7.

Why are so many people surprised then when Apple announced that they are blocking other languages (3.3.1) on the iPhone platform or about yesterday’s news (which we don’t know if they are rumors or facts) that no software will run on Mac OS X 10.7 without being approved and signed by Apple? (according to Rixstep)

I have seen many write in their blogs and post tweets saying that “Steve Jobs has Just Gone Mad” and that “can’t be true” with the context of OS X 10.7 possibly locking the ability to publish apps without Apple’s approval.

The reason many are surprised is that Apple always appealed to the young generation, and we think of Apple as an “open minded” young company. Most designers are using a Mac. Apple store in Midtown and Soho are sexy, and they managed to fool us all with the coolness factor. In reality these are just marketing techniques, and the reality is that Apple’s executive don’t have an open minded mentality - they never had one!

img_1278

Apple has moved from having less than 4% on Apple Computer to close to 10% of USA Market Share today putting it in 4th place behind HP, Dell, and Acer (according to osxdaily). The iPhone is capturing 72% of the smartphone market in Japan (according to BusinessWeek). Additionally, the iPod has half the digital music player market, and iTunes sells 70% of all legitimate music downloads (according to USAToday). Today Apple is capable of putting more restrictions and “crossing lines” since they have much more than 4% market share, and if they piss off some users it won’t affect them much. It can actually benefit them with Joe Schmoe enjoying a great experience on Apple’s computers and devices. Joe Schmoe may not be able to play all the games and surf all the websites, but overall the Apple experience will be superior to the PC experience.

Adobe Open Screen Project with WORA (Write once, run anywhere) concept is a threat to Apple’s closed ecosystem model. Even AIR on Mac OS is a threat since they don’t have full control over what the user installs which may interfere with their possible plan to force people into using iTunes for installing all their software.

Adobe has handed Apple a large development community on a silver platter that can help create more appealing applications and games for iPhone platform. Additionally, Unity3D has helped the iPhone platform with Unity powered games in the top 100 list and some amazing games such as Battle Bears, Zombieville, or Monster Trucks Nitro.

Steve Jobs sees these platforms as a threat to Apple’s closed ecosystem, and it appears that Apple would rather lose a small market share (which is growing fast anyway) rather than allow someone to tear their walled garden down. Some market share reports show Mac OS X has reached a market share of 29% (see here).

However, Apple can’t keep the technology to itself. Just as it happened with PCs, I believe that Apple’s continuous attempt to control music, applications, games and others may be the reason Apple will sink. Already, according to reports iPhone dominates but Android is the fastest growing OS.

sinkship

15
Apr

Flex data binding pitfalls: common misuses and mistakes - article on Adobe Developer Connection

My article about Data Binding is up on Adobe Developer Connection. Data binding is one of the most used and useful features when building Flex and Adobe AIR applications. At the same time, however, data binding can slow application initialization and cause frustration when developers don’t fully understand how the mechanism works. It is a good idea to make sure you are using it correctly and only when needed. In this article, I’ve compiled a list of ten common pitfalls and mistakes that developers are susceptible to when building an application that uses data binding.

Read the article here:

Flex data binding pitfalls: common misuses and mistakes

screen-shot-2010-04-14-at-111857-pm

Cheers :)

30
Mar

Improve Flash Catalyst Performance

@polyGeek reminded me today (see blog post here) about increasing the memory size allocated to Eclipse and made me wonder if I can do the same thing to FlashCatalyst.

You probably noticed that Flash Catalyst is often slow. As you may know Flash Catalyst is based on Eclipse IDE and just like any Eclipse instance you can improve performance simple by tweaking the heap size and permSize to maximize performance. You should give the VM as much ram as you can and set the min and max values (the same) to avoid resizing of your memory.

On PC change “Adobe Flash Catalyst CS5.ini” located here
C:\Program Files\Adobe\Adobe Flash Catalyst CS5

On MAC: Under /Applications/Adobe\ Flash\ Catalyst\ CS5 Adobe Flash Catalyst\ , select Adobe Flash Catalyst CS5.app and right click the app > select “Show Package Contents”, and then traversed to find the location of the “Adobe Flash Catalyst CS5.ini” file.

Flash Catalyst comes with larger memory allocation than Flash Builder, see below:


-clean
-vmargs
-Xdock:icon=../Resources/fc_app.icns
-Xdock:name=Flash Catalyst
-XstartOnFirstThread
-Xms512m
-Xmx512m
-XX:MaxPermSize=256m
-XX:PermSize=64m
-Dorg.eclipse.swt.internal.carbon.smallFonts
-Dorg.eclipse.swt.internal.carbon.noFocusRing

You can increase the Xms and MaxPermSize to improve performance.
I have 4GB RAM on my MBP machine and changed the heap to 1024m and a permSize to 512m.


-Xms1024m
-Xmx1024m
-XX:MaxPermSize=512m

I notice significant improvement. Cheers :)

29
Mar

FXGStringConverter - converts FXG text string to component during runtime

There are times were you need to take an FXG (Flash XML Graphic) from Photoshop, Illustrator or Flash Catalyst and load it during runtime. FXG is usually handled by the MXMLC which turns the declarative language into ActionScript code. The utility class will do just that and convert the text string into ActionScript code which can than be added to the display object or manipulated during runtime. Take a look at a simple implementation which allow the user to insert text string and it will turn it into a group component:


<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"
	minWidth="955" minHeight="600">

	<fx:Script>
		<![CDATA[
			import com.elad.framework.utils.fxgconverter.FXGStringConverter;

			protected function button_clickHandler(event:MouseEvent):void
			{
				var comp:Group = FXGStringConverter.convertFXGStringToComponent( textArea.text, true );
				group.addElement( comp );
			}			

		]]>
	</fx:Script>

	<s:TextArea id="textArea" width="300" height="200" />
	<s:Button id="button" x="14" y="214" label="Submit" click="button_clickHandler(event)"/>
	<s:Group id="group" width="500" height="500" x="0" y="300" />	

</s:Application>

screen-shot-2010-03-30-at-92633-am

Although I tested it on all the code that I needed, keep in mind that the code is still in alpha and is not fully tested, so I am sure there may be cases where it will fail. Also group your FXG code since I haven’t tested it fully with all types of code. See FXG sample below:


<s:Group id="groupSample1">
     <s:Ellipse id="ellipse" width="30" height="30">
          <s:fill>
               <s:SolidColor color="0x000000"></s:SolidColor>
          </s:fill>
      </s:Ellipse>
</s:Group>

The code is published as open source and hosted under my private library:
http://github.com/EladElrom/eladlib

20
Mar

Tip: calculate properties such as position and measurements for Flex Spark Label component

There are cases where you need to find out position and measurements for Flex Spark Label component. There are many cases where you will find the code useful, such in case you need to calculate the width of a text string in pixels during runtime. Take a look at the following code snippet:


var label:Label = new Label();
label.regenerateStyleCache( false );
var textMetrics:TextLineMetrics = label.measureText( name );
var textWidth:int = textMetrics.width;

textWidth will hold the text width in pixels.

TextLineMetrics is part of the TLF framework and contain information about the text position, measurements etc. See more here:
http://livedocs.adobe.com/labs/textlayout/flash/text/TextLineMetrics.html

label.regenerateStyleCache(false); is used to ensure that the label component updated the metrics since many times commit properties or invalidate properties wouldn’t do the trick.

There are cases where you need to truncate (remove text and add dot dot dot) the text of a Spark Label once the text exceed a certain width. To do that you can add the following command:


import spark.components.supportClasses.TextBase;
TextBase.mx_internal::truncationIndicatorResource = "...";

Make sure you also add maxDisplayedLines="1" to the label component.

20
Mar

Tutorial - Drag And Drop an FXG element

One of the most used visual development in Flex is drag and drop functionality I am using Flex 4 SDK since early iteration and really enjoyed the new Spark component and FXG (Flash XML Graphic) architecture. I was asked last week by one of my developer to help him understand how to work with FXG code and apply drag and drop functionality, so I created a quick POC (Proof Of Concept) and decided to share it in case someone have a similar application and running into difficulties. Before we get started I want to point out the the code is written very quickly and can be improved. I only wanted to give the basics and you can take it from here.

Drag and drop operation consists of three steps:

  • Initiation
  • Dragging
  • Dropping

To drag FXG element is similar to how you would create drag and drop in Flex3, since the FXG can be wrapped in a Group which extends GroupBase (which than extends UIComponent), however there are few changes in terms of wrapping the FXG as an object that the DragManager recognize.

Let’s take a look.

We set two components: a List to hold the FXG components and a Group component to hold the drop items, see below:


	<!-- source -->
	<s:List id="list" mouseDown="mouseDownHandler(event)"
			x="0" y="0"
			skinClass="components.DataList"
			width="169" height="200"/>

	<!-- dest -->
	<s:Group id="group"
			 width="200" height="200"
			 x="190" y="0"
			 dragEnter="dragEnterHandler(event);"
			 dragDrop="dragDropHandler(event);">

		<s:Rect top="0" left="0" right="0" bottom="0">
			<s:fill>
				<s:SolidColor color="0xCCCCCC" />
			</s:fill>
		</s:Rect>

	</s:Group>

Once the user click mouse down on an item in the list the event handler start tracking the mouse move event and will call the startDragItem method:


// holds the selected index
private var selectedIndex:int;

public function mouseDownHandler( event:MouseEvent ):void
{
	selectedIndex = (event.currentTarget as List).selectedIndex;
	this.addEventListener(MouseEvent.MOUSE_MOVE, startDragItem );
}

The startDragItem method will pick the item that was selected and cast it as a ComponentVO and set the following:

  • drag source
  • drag initator
  • set the image source
  • set the data

Once we create all that information that is needed you can set the DragManager as follow:
DragManager.doDrag( dragInitiator, dragSource, event, dragProxy );

See code below:


private function startDragItem( event:MouseEvent ):void
{
	var selectedItem:ComponentVO = collection.getItemAt( selectedIndex ) as ComponentVO;

	// drag source
	var dragSource:DragSource = new DragSource();

	// drag initator
	var dragInitiator:Group = selectedItem.fxg;

	// create an image
	var bitmapData:BitmapData = getBitmapData( selectedItem.fxg );
	var bitmap:Bitmap = new Bitmap( bitmapData );

	// set the image source
	var dragProxy:Image = new Image();
	dragProxy.source = bitmap;

	// set the data
	dragSource.addData( selectedItem, "ComponentVO" );

	DragManager.doDrag( dragInitiator, dragSource, event, dragProxy );
}

// retrieve the bitmap data of a component
private function getBitmapData( target:UIComponent ):BitmapData
{
	var bitmapData:BitmapData = new BitmapData( target.width, target.height );
	var matrix:Matrix = new Matrix();
	bitmapData.draw( target, matrix );

	return bitmapData;
}

The destination have event handlers to trace drag enter and drag drop events:
dragEnter=”dragEnterHandler(event);” dragDrop=”dragDropHandler(event);”

The handlers will allow adding the item to the destination component and add the actual FXG component:


// drop item
private function dragDropHandler( event:DragEvent ):void
{
	this.removeEventListener( MouseEvent.MOUSE_MOVE, startDragItem );

	var selectedItem:ComponentVO = event.dragSource.dataForFormat('ComponentVO') as ComponentVO;
	selectedItem.fxg.x = 0;
	selectedItem.fxg.y = 0;
	this.group.addElement( selectedItem.fxg );
}

private function dragEnterHandler( event:DragEvent ):void
{
	var dropTarget:Group = event.currentTarget as Group;

	if (event.dragSource.hasFormat('ComponentVO'))
	{
		DragManager.acceptDragDrop(dropTarget);
	}
}

Last part is to create static FXG component we can use. You can load the object or runtime or pass it from a different class or service, this example is just a POC so I kept it simple but you get the idea. Once the creationCompleteHandler is called the collection will be filled with the two objects:


// handles creation complete
protected function creationCompleteHandler(event:FlexEvent):void
{
	collection = new ArrayCollection();

	collection.addItem( new ComponentVO( "Item1", groupSample1 ) );
	collection.addItem( new ComponentVO( "Item2", groupSample2 ) );

	list.dataProvider = collection;
}

The sample FXG code will look as follow:


	<!-- Holds a sample FXG code -->
	<s:Group id="groupSample1">
		<s:Ellipse width="30" height="30">
			<s:fill>
				<s:SolidColor color="0x000000">
				</s:SolidColor>
			</s:fill>
		</s:Ellipse>
	</s:Group>
	<s:Group id="groupSample2">
		<s:Ellipse width="30" height="30">
			<s:fill>
				<s:SolidColor color="0x00FF00">
				</s:SolidColor>
			</s:fill>
		</s:Ellipse>
	</s:Group>	

Complete code is listed below:


<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"
			   minWidth="955" minHeight="600"
			   creationComplete="creationCompleteHandler(event)">

	<fx:Script>
		<![CDATA[
			import mx.collections.ArrayCollection;
			import mx.controls.Image;
			import mx.core.DragSource;
			import mx.core.UIComponent;
			import mx.events.DragEvent;
			import mx.events.FlexEvent;
			import mx.managers.DragManager;

			import vo.ComponentVO;

			// holds the collection
			private var collection:ArrayCollection;

			// holds the selected index
			private var selectedIndex:int;

			public function mouseDownHandler( event:MouseEvent ):void
			{
				selectedIndex = (event.currentTarget as List).selectedIndex;
				this.addEventListener(MouseEvent.MOUSE_MOVE, startDragItem );
			}

			// handles creation complete
			protected function creationCompleteHandler(event:FlexEvent):void
			{
				collection = new ArrayCollection();

				collection.addItem( new ComponentVO( "Item1", groupSample1 ) );
				collection.addItem( new ComponentVO( "Item2", groupSample2 ) );

				list.dataProvider = collection;
			}

			private function startDragItem( event:MouseEvent ):void
			{
				var selectedItem:ComponentVO = collection.getItemAt( selectedIndex ) as ComponentVO;

				// drag source
				var dragSource:DragSource = new DragSource();

				// drag initator
				var dragInitiator:Group = selectedItem.fxg;

				// create an image
				var bitmapData:BitmapData = getBitmapData( selectedItem.fxg );
				var bitmap:Bitmap = new Bitmap( bitmapData );

				// set the image source
				var dragProxy:Image = new Image();
				dragProxy.source = bitmap;

				// set the data
				dragSource.addData( selectedItem, "ComponentVO" );

				DragManager.doDrag( dragInitiator, dragSource, event, dragProxy );
			}

			// retrieve the bitmap data of a component
			private function getBitmapData( target:UIComponent ):BitmapData
			{
				var bitmapData:BitmapData = new BitmapData( target.width, target.height );
				var matrix:Matrix = new Matrix();
				bitmapData.draw( target, matrix );

				return bitmapData;
			}

			// drop item
			private function dragDropHandler( event:DragEvent ):void
			{
				this.removeEventListener( MouseEvent.MOUSE_MOVE, startDragItem );

				var selectedItem:ComponentVO = event.dragSource.dataForFormat('ComponentVO') as ComponentVO;
				selectedItem.fxg.x = 0;
				selectedItem.fxg.y = 0;
				this.group.addElement( selectedItem.fxg );
			}

			private function dragEnterHandler( event:DragEvent ):void
			{
				var dropTarget:Group = event.currentTarget as Group;

				if (event.dragSource.hasFormat('ComponentVO'))
				{
					DragManager.acceptDragDrop(dropTarget);
				}
			}

		]]>
	</fx:Script>

	<!-- Holds a sample FXG code -->
	<s:Group id="groupSample1">
		<s:Ellipse width="30" height="30">
			<s:fill>
				<s:SolidColor color="0x000000">
				</s:SolidColor>
			</s:fill>
		</s:Ellipse>
	</s:Group>
	<s:Group id="groupSample2">
		<s:Ellipse width="30" height="30">
			<s:fill>
				<s:SolidColor color="0x00FF00">
				</s:SolidColor>
			</s:fill>
		</s:Ellipse>
	</s:Group>	

	<!-- source -->
	<s:List id="list" mouseDown="mouseDownHandler(event)"
			x="0" y="0"
			skinClass="components.DataList"
			width="169" height="200"/>

	<!-- dest -->
	<s:Group id="group"
			 width="200" height="200"
			 x="190" y="0"
			 dragEnter="dragEnterHandler(event);"
			 dragDrop="dragDropHandler(event);">

		<s:Rect top="0" left="0" right="0" bottom="0">
			<s:fill>
				<s:SolidColor color="0xCCCCCC" />
			</s:fill>
		</s:Rect>

	</s:Group>

</s:Application>

screen-shot-2010-03-20-at-25531-pm

Download the complete FXP code from here:
http://elromdesign-example-codes.googlecode.com/files/DragDropFXG.fxp

18
Mar

MIX10 recap from a Flash/Flex developer standpoint

I am sitting at the airport waiting for my flight to leave back to New York City and trying to gather my thoughts about MIX 2010. This was the first time I was attending Microsoft MIX conference and as someone that spent the last few years focusing solely on Adobe’s technologies, this is definitely out of my comfort zone. I have done C-Sharp/ C++ programming years ago and used Visual Studio 2002/2003 but haven’t kept in touch with Microsoft development tools since then. I had a great time hanging out with the Flash community friends such as @TheFlashBum @adamflater @jefftapper @jesterxl, @Rhall, @__Ted__ , as well as my new Microsoft friends such @adkinn, @brianjo and @thedavedev.

26

It’s definitely refreshing to be involved and know where other vendors such as Microsoft are heading and it actually helped me better understand Adobe’s road map better. It appears that Microsoft is focusing on three main areas in regards to the Web:

  • Mobile
  • RIA
  • Browser

Microsoft is known for sitting on the fence and waiting to see what works and then to launch an assault using their 8,000 engineers’ brainpower. Microsoft advancement is an attempt to ensure Microsoft has a solution for the technology advancement from Apple, Adobe and Mozilla and provides their developers the ability to stay with Microsoft without wondering around to other vendors. It’s like going to a 5-star resort where you get the hair dresser, the beach, restaurants, jewelry stores, a pool and maybe even a golf course, so you have no reason to leave the resort, however, staying at the resort you don’t get the culture and some of your culinary experiences are artificial.

You need to be adventures and explore, which is something the Flash community is not afraid of. Many Flash professionals have embraced other technologies such as open source projects GIT or other 3rd party vendors such PHP, Objective-C and others. It’s not rare to hear that someone is involved in Flash and Unity3d, however, from talking to others at MIX conference, I rarely heard many talking about any other technologies other then MS, and I asked.

Additionally, since MS is sitting on the fence and waiting to see what’s the next big thing, they are paying a price and everything that I have seen isn’t that impressive in terms of showing off new innovative technologies. With that said, I was extremely impresses by the speed and efficiency of Microsoft to reach what took other companies took years to achieve and how they can partner with other large corporations. For instance:

  • Microsoft claims that they achieved 60% penetration with Silverlight plugin. Even if the numbers are 55% that’s pretty impressive considering the fact that other plug-ins took years to achieve that type of penetration.
  • Microsoft Expression Blend is the equivalent of Flash Catalyst. The product was in the works since 2006 and first released in 2007 and the latest built is pretty impressive considering that MS does not have a long background with design and the tool can even allow importing illustrator, Photoshop and CS4 FXG code.

Windows Phone 7

The biggest announcement was the release of Windows Phone 7 later this year. Let’s look back for a second. In 2004, Windows Mobile took about 23% of worldwide smartphone sales, however, by 2009, it’s shares dropped to 7.9% (according to Gartner). The latest version of Windows Phone 7, codenamed “Photon” is Microsoft’s attempt to increase market share.

Microsoft is going to dictate the hardware requirements and require the OEMs (Original Equipment Manufacturer) to include 3 Hardware buttons (Back, Search and WinKey) as well as other hardware requirements such as Touch Displays with 4 sensor points, A-GPS, Accelerometer, Compass, DX9-capable GPU, Proximity and Light Sensors, 256MB Flash RAM and 8GB Storage Memory, HQ camera with Flash and a camera button.

Keyboard and screen sizes of 800×480 or 480×320 are optional but it lacks some basic features such as copy-paste. The latest phone is MS attempts to move forward and be able to compete with Apple and Google. In terms of software, Mobile Phone 7 will include Office, Outlook, IE 7.5, XBOX Live, Social Networking and others. The feature that impressed me the most was the physics API that is used in XBOX and is available for Windows Mobile and SL.

In terms of the business model it is similar to how Microsoft sells Windows OS. Microsoft will make the software for Windows Phones, and OEMs pay Microsoft a license fee for each device they ship. Developers can monetize by selling apps on the Windows Phone Marketplace.

Microsoft is taking a similar approach to Apple’s walled garden and requires certifying apps before they are added to the app store. Developers can offer free apps, such as ad-supported apps, can sell apps by downloading like the iPhone app model, and a “freemium” model in which they could offer free-trial app with an option to buy an upgrade. Developers would get to keep 70% while Microsoft keeps 30%.

From what I have seen so far the device has a while to go before it can really compete with the iPhone. I find it surprising that Apple announced the iPhone in January 2007 and since then they haven’t added any major innovations, in my opinion. At the same time I haven’t seen one Smartphone that can truly provide a GUI experience that is as superior as the iPhone, not even the Droid. I believe that Microsoft needs to start taking some risks and instead of doing “catch up”, provide real software innovations, for instance: context awareness. It would be neat if our Smartphone can recognize that we are at the movie theater based on the GPS and turn the ringer off or recognize that we are sleeping based on the accelerometer is at a horizontal position for a while and go into an hibernation mode.

During the conference I was asking by some MS executives whether the software will include Flash Player 10.1 or at least Flash Lite 3 but I couldn’t get a straight answer, not even off the record. Historically, MS always supported Flash Lite even when they had to purchase the license (prior to the Open Screen Project) but I suspect that it had to do with the underlining OS. During the Keynote, MS pointed out that the device will support the complete full version of SL except for certain graphics APIs so the device is surely capable of deploying FP10.1. But now that MS is competing with Adobe directly, I wouldn’t be surprised if we wont see FP in first release.

Internet Explorer 9

The other big news was IE9. MS has decided not to embrace Webkit and continue their own development. In fact, the new IE9 supports CSS3, HTML5 as well as GPU.

I think that what stood out the most to me is the performance – the new IE9 is faster. How fast? Almost as fast as Safari and appears to handle graphics in some cases better than Chrome or Safari due to the usage of the GPU.

MS engineers appear to be getting very excited during the keynote and other preso by HTML5’s ability to turn few images in 3D space using the GPU. Later I went to a preso by @JasonCWeber about High performance Optimization For Website. Jason pointed out few times stuff like “this type of amazing graphic experience” when he presented the same 3D images floating in space using the GPU. Yes, I agree it’s impressive for HTML but we are in 2010?!

110

Expression Blend

Microsoft Expression Studio is a suite of tools for designing Silverlight application. You can create & import comps from CS4 and using intuitive tool, and add the interactivity, as well as generate code. The tool is impressive and was built from the ground up using .NET but that’s also the caveat - the tool is currently only available for PC. How many designers do you know that use PC? And in fact I asked a few people at MS and they told me that Mac only accounts for 3% of the market, but that’s the 3% you want!

Just as with Flash Catalyst I wonder who is going to be using this tool. Apparently, MS has created a new role called Designer-Developer. Who would be doing this type of development? I attended a great preso by Adam Kinney about Microsoft Expression Blend. MS is attempting to lure Flash designer and developers, however, I don’t see any advantage at this point for Flash developers to start using the tool. MS needs to solve the chicken and the egg problem first. Professionals need work and to be asked to build an application using Silverlight and MS needs to start building a strong portfolio as well as help agencies sell in order to create a case that Silverlight can produce the same type of applications as we see today with Flex. Yes NetFlix is using Silverlight but I haven’t seen any great Website developed with SL. In fact, even SL website needs a facelift.

Additionally, as Flash/Flex developers, we are all used to being the ones converting graphics into code and creating a compelling user experience. Having paintbrushes or the right dancing shoes is useless without having artists capable of creating compelling apps. I believe both Adobe and MS are trying to convince us that UXD people exist. I only know of about 5 UXD people; the rest of the UXD is done by developers.

43

Coming to the MIX conference and seeing MS trying to replicate design and UXD experiences we at the Flash Community are doing for years makes it clear to that RIA is moving into main stream. At this point Microsoft is the underdog since Adobe is doing RIA since Flex 1.5 and even before that with some smart Flash apps so yes Adobe has reasons to worry but as MS will try to catch up, Adobe has an opportunity to innovate and ensure MS is always the underdog. Otherwise, Flex can die. I also noticed that having MS truck heading your way makes some people in the Flash community pretty nervous about their livelihood. There are about a million Flash developers which most of them don’t devote their entire time to RIA or enterprise development, but building banners and touching the technology on rare occasions, so I don’t believe anyone has to worry. At the same time, about 30 mins ago I got a call from a potential side client that told me that his company’s board of directors are leaning toward Silverlight for creating a program that streams video and allows saving the data into the user’s desktop.

Visual Studio 2010, .NET Framework 4.0 and Silverlight 4

Visual Studio finally got the visual update and a developer can work in Designer Mode just like in FlashBuilder, which is a nice feature for Silverlight development. While watching the presentation, I saw some nice features from the IDE that I would die to have in FlashBuilder. But once again, I am not sure if I am quite ready to start working on a PC.

MS is doing what Flash developers are asking for years and teamed up with EBay to open an equivalent of the iTunes app store for developers, which will help developers to monetize and sell Silverlight software. MS knows how to make money and Adobe should take notes. MS is also going to release an open source framework for tracking usage patterns for Silverlight apps running in or out of the browser.

Conclusion

I was very fortunate to be invited to the event by Microsoft and I will be in touch with my new MS friends, however, tomorrow morning I will be still doing Flash unless I have requests from clients for Silverlight applications.