Category search : as3/mxml...

(23 results found)

ActionScript 3 in Sublime Text 2 - simply refreshing!

Thu Sep 8 02:02:03 2011

I had a really pleasant surprise today when I just happened to stumble upon a great little text editor called Sublime Text. Sublime Text 2 is currently at build version 2111 and is still in its beta stage... but boy is it good. It supports many of the major features that I feel have been sadly lacking from TextMate - i.e. split view coding, rich text input such as Japanese (a big one for me), a minimap, full screen and distraction free views - as well as macros and snippet support of course - and anything else I can think of that I need and use on a daily basis.

To get set up to compile for AS3, first off go download it at the Sublime Text website. Then once it's safely installed and inside your Applications folder (if on a mac), fire it up. At first glance, it actually looks a lot like TextMate, but for me has a bit more appeal.

You will need to add what's called a Build System in order to run the build command mxmlc . To do this, go to Tools > Build System > New Build System... . A new file should open called ' untitled-sublime-build '.

Copy the following json into that file, of course substituting the 'location_of_flex_sdk' for the real location of the sdk...

{
    "cmd": [" location_of_flex_sdk /bin/mxmlc", "$file"],
    "selector": "source.actionscript"
}
and save the file as ActionScript.sublime-build in Library/Application Support/Sublime Text 2/Packages/ActionScript/ .

Quit and restart Sublime. Now, write a little hello world in AS3 (whatever you like) and save it anywhere you like.

Now all that's left is to press command + b and you should see the build take place.

To work in split screen, go to View > Layout and choosing a layout you'd like.

Pretty nice, me thinks. Can't wait to see how this baby is going to turn out. Looks very promising.

Graphics Optimization for the Adobe iPhone Packager

Fri Dec 24 05:33:13 2010

I have been doing some looking around and to be honest there isn't much that I have found useful in regard to graphics optimization for the iPhone Packager. To be quite frank, I may even be as bold as to say that it appears quite useless compared to a lot of other solutions available. That of course does not go for Adobe's efforts for Android. I'm sure that with the increase in great mobile devices that offer Android OS, the performance will just keep getting better. However, what do we do in the meantime for ActionScript on the iPhone? Well, here's something that may not be very practical but I have found that it boost performance of graphics on the device.

Most will know by now that using cacheAsBitmap = true; and cacheAsBitmapMatrix = new Matrix() along with setting the renderingMode to gpu helps performance considerably and I can vouch for that.

However, I have been hearing a lot of talk about how using Bitmaps also helps performance. This I have found not to be so true, as when I compile an .ipa file using -renderingdiagnostics, every bitmap that I have every tested lights up a bright red (not good). All vector graphics, including FXG graphics display in a nice green. The frame rate is always much higher for vector graphics and FXG too, provided that nothing too strenuous is being done to them.

Now this is what I find interesting about all this. When I create an FXG file containing one of the .png files that display in red under -renderingdiagnostics, and then import said FXG file and use cacheAsBitmap = true; and cacheAsBitmapMatrix = new Matrix() with gpu set as the renderingMode, I get much better performance than just using a Bitmap by itself.

I don't really know why this occurs and I nothing I have read gives any indication of this, but through my own experiments, that is what I found. Please let me know if anyone finds a way to use bitmaps that display in green under -renderingdiagnostics. Or have I got it all wrong, and there is no way to cache an actual Bitmap? If so, then that is just silly!

Come on Adobe, I know you are working hard but throw us a bone!

Dynamic Classes in ActionScript 3

Mon Nov 29 23:45:29 2010

Dynamic classes in AS3 are a cool feature of the language. They allow you to add properties to the dynamic class at run time, which is something that is not possible with other types of class. It is important to note however that dynamic class are a little more memory intensive, due to the fact that they create what is called a 'hash table' to store the properties/methods added at runtime.

The Dynamic Class - MyDynamicClass


package{	
   import flash.display.*;
	
   public dynamic class MyDynamicClass extends MovieClip{
      public var firstName:String = "Ben";
      private var age:String = "28";

      public function MyDynamicClass(){
			
      }
   }
}

Public Class Main (instantiates MyDynamicClass)


package{	
   import flash.display.*;
   import MyDynamicClass;
	
   public class Main extends MovieClip{
      private var d:MyDynamicClass = new MyDynamicClass();

      public function Main(){
         trace(d.firstName); // outputs "Ben";	
         trace(d.age); //outputs undefined

         d.gender = "Male";
         trace(d.gender); //outputs Male
         delete d.gender;
         trace(d.gender) //outputs undefined
      } 
   }
}

Looking at MyDynamicClass, you will notice that it contains 2 variables - firstName and age. The property firstname is accessible by Main because it is public, whereas age is not accessible because it is private. Nothing new there! But inside the Main class we then add the dynamic property gender, which traces out just fine. Using the keyword delete allows the removal of dynamic properties, which in turn, puts them up for garbage collection. In the Main class example, g.gender is deleted on line 14 and when a trace is performed on that property on line 15 you will see that it now outputs undefined as it is no longer available to the class.

I'm not entirely sure how practical a technique this is and I would suggest that properties and functions should always be defined inside the classes they are meant for, as it makes it slightly more difficult to see exactly what a program/class is doing. However, I think that if you don't plan on passing your code on to anyone else, it may be the quick 'escape' you need if you're too lazy to back into an imported class a defined the property. Just be warned though that classes that extend a dynamic class are not dynamic in themselves, so be prepared for some irritating error messages from time to time! :)

Smoothing Loaded Images in AS3

Wed Jun 23 06:11:51 2010

Today, there I was, sitting at my desk working hard on a project involving loading images into a ActionScript constructed gallery. I needed the images in the gallery to animate and scale, as one would expect to be able to do with rich internet content.

Herein the problem lies, because the images looked very pixelated when they did anything other than just remain still.

Now, this isn't a big problem if you know how to go about it the right way, but I would imagine that there are tons of people out there who need to do the same kind of thing in their galleries, and probably 9 times out of ten are frustrated by the quality of the images output in the flash player. After all, rich internet applications should display rich image content. Then it hit me! Why not write a little about it here and spread the message that, although the flash player can sometimes be a CPU hog, it is something special, even when dealing when dealing with images.

As you will have probably seen by now, in the top left of this post there is a .swf file playing a scaling image, which reads "I love AS3" (and I admit proudly that I do). At the bottom of the swf there is a button, which when pressed will add/remove bitmap smoothing to the image loaded. Smoothing in ActionScript 3 is surprisingly simple and can be done by setting the smoothing property of any Bitmap instance to true. Take a look at the example below.

var ldr:Loader = new Loader();
addChild(ldr);
ldr.scaleX = ldr.scaleY = 5;
ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
ldr.load(new URLRequest("myImage.jpg"));

function imageLoaded(event:Event):void{
   var contentToSmooth:Bitmap = event.target.content;
   // contentToSmooth.smoothing = true;
}

If we were to compile this code as it, assuming we've entered the correct URL to the image, we should see our image scaled by 5x and looking quite pixelated depending on how high the quality is of the image used. Now all we have to do to see the effects of smoothing is uncomment line 9 by removing the // from the beginning and recompile. This time you should notice a much less pixelated image displayed, even at 5x the size.

If you're interested in the example at the top left of this post, you can download the source code below.

Download BitmapSmoothing source code

Loading Fonts at Runtime with latest Flex 4 SDK

Tue May 11 03:27:29 2010

I wrote a post a while back about loading fonts at runtime. Nothing there has really changed, but I did want to clarify one thing on here. I just discovered that when embedding fonts with the latest Flex 4 SDK, I got an error with the following

[Embed(systemFont='OCR A Std', 
fontName="OCR",
mimeType="application/x-font",
unicodeRange="U+0041-U+005A")]

The error read:
Error: exception during transcoding: Cannot embed local font 'nameOfFont' as CFF. The CSS @font-face 'local()' syntax is not supported. Please specify a path directly to a font file using the 'url()' syntax. For [Embed] syntax the 'systemFont' attribute is not supported. Please specify a path directly to a font file using the 'source' attribute.

I found that adding the following solved this problem.

[Embed(systemFont='OCR A Std', 
fontName="OCR",
embedAsCFF='false',
mimeType="application/x-font",
unicodeRange="U+0041-U+005A")]

" No transcoder registered for mimetype 'text/fxg' " Error

Sat May 8 17:43:39 2010

Well, this has really bugged me for a while now... I've been using an older version of the Flex 4 SDK until recently and have never had this problem. When I downloaded the latest nightly, I was struck with the fear that I would never again be freely able to use FXG the way I had previous. I just couldn't understand why the Flex 4 SDK wouldn't be able to transcode Adobe's shiny new toy - FXG. It just didn't make sense. I actually wrote another rather popular post about how to embed FXG in ActionScript which showed the following method of using FXG.

The following doesn't seem to work using the latest Flex 4 SDK releases


[Embed(source='Flower.fxg')]
private var Flower:Class;		
private var flower:Sprite = new Flower();

But why wouldn't something that worked before, work now? For a moment, I thought it was a way to make you buy software that supported this feature, but that didn't make sense either, since the SDK is free as well as having an open source version.

Then it hit me. I'd remembered watching a video that someone from Adobe (at least he said he was) had posted online. The video showed something along the following lines

This seems to works fine!


import Flower;
var flower:Flower = new Flower()
addChild(flower);

I could never get this to work in the older versions of the Flex 4 SDK but that's right folks! What was pretty simple before has become even simpler! Now just treat the FXG graphic as you would any other class and the magic is retained. In the words of David Bowie, "Wham bam thank you mam!"

Trace Statements with the FLEX SDK

Fri Apr 30 00:57:05 2010

This is a topic I have long since intended to write about, but never got round to it. Well, anyway... trace statements in flex/flash are something that I would imagine we all use all the time, mostly for debugging purposes. There is a great little extension for the Firefox plugin FireBug called FlashBug, which allows trace statement output directly from within the browser. It is also possible to view this output via Terminal on OSX/Linux and command prompt on Windows. However, there are a few things that need to be set up.

First create a file call "mm.cfg" and place it in the following location:

On OSX: /Library/Application Support/Macromedia/mm.cfg

On Win: C:Documents and Settingsusernamemm.cfg

On Linux: home/username/mm.cfg

Next open the mm.cfg file and type the following inside.

ErrorReportingEnable=1

TraceOutputFileEnable=1

It may be obvious, but ErrorReportingEnable controls the ability to view error output and TraceOutputFileEnable controls the ability to view trace output. Setting each of these values to 1 turns these properties on. If, for example, you didn't want to view error output, simply turn the 1 to a 0, or delete the line ErrorReportingEnable.

Anyway, moving on. Create an ActionScript file that uses trace statements. I've pasted an example below for convenience. For test purposes, just save it as Main.as.

package{	
   import flash.display.*;
	
   public class Main extends MovieClip{

      public function Main(){
         trace("Trace output is working");
      }
   }
}

Next we need to compile it. If you aren't sure how to do this, you can take a look at my other post: Compile AS files with Flex SDK, which gives a more detailed "how to", or simply use Terminal/Command Prompt to open up fsch found inside the bin folder of the flex sdk (which you should already have), and type the following, obviously swapping in the location and file names where necessary.

mxmlc -o=output_location/your_filename.swf -file-specs=your_file_location/Main.as

This should compile the Main.as file and you should be left with a .swf file saved at the location you entered. Before you open this file, you will need to install the flash debug player from the Adobe website. You will find it under Debugger Versions. Once you have that installed run the swf file. A file called flashlog.txt containing any errors and/or trace output will be created in the following location:

On OSX: /Users/username/Library/Preferences/Macromedia/Flash Player/Logs/flashlog.txt

On Win: C:Documents and SettingsusernameApplication DataMacromediaFlash PlayerLogsflashlog.txt

On Linux: home/username/Macromedia/Flash_Player/Logs/flashlog.txt

To view this information in real time simply use FlashBug with Firefox or type the follow into Terminal

tail -f /Users/{username}/Library/Preferences/Macromedia/"Flash Player"/Logs/flashlog.txt

For added convenience to anyone using TextMate, go to Bundles > Bundles Editor > Show Bundle Editor and click on the little plus sign on the bottom left hand side of the bundle editor window. Choose New Command and name it whatever you want. I named it Tail Output. Make sure Save:Nothing, Input:None and Output:None are selected. Next enter the following content into the Command(s) window changing {username} to the name of your home folder on OSX (This is just a little bash program I wrote to tell Terminal to tail the FlashLog.txt file).

Note* tail -f and /User/{usersname}... should be on the same line.

#!/bin/bash
 
aplscr="tell application "System Events" to set terminalRunning to (exists process "Terminal")

tell application "Terminal" to activate
tell application "Terminal" to do script "tail -f 
/Users/{username}/Library/Preferences/Macromedia/'Flash Player'/Logs/flashlog.txt" 
in front window" osascript -e "$aplscr" &>/dev/null &

Next set Activation: Key Equivalent, and enter whatever shortcut you want to activate the command in Terminal. I chose ⌘T (T for tail). For the Scope Selector, enter source.actionscript.3.

After all that's done, it's probably best to quit and restart TextMate. Now all you have to do to start viewing the errors and trace out is press your Key Trigger in TextMate while editing an ActionScript file and Terminal should start up and read out all the trace statements.

And that's it! By this point, if you've done it right, you should be getting readout on Errors and Trace statements and all should be well.

Removing Duplicates from Arrays in AS3

Tue Apr 20 06:09:33 2010

Of late, I haven't been posting much on here because I am a little bogged down with work right now. I'm working on a few projects at the same time which is really taking up all of my time. One such project, however, gave me an interesting problem whereby I needed to remove duplicates from an array that was being looped, and on each loop items in the array were removed from the flash display list. Thus, if the same item was found again in the array during another loop and didn't exist anymore in the display list, it caused an error. Here's how I got around it.

package{	
   import flash.display.*;
	
   public class Main extends MovieClip{

   public function Main(){
      var array:Array = ["1973", "1963", "1999", "1879", "1879", "1963", "1999", "1973"];
      trace(array); //traces the original array	in which each item occurs twice;
		
      var newArray:Array = removeDuplicates(array);
      trace(newArray);//traces 1973,1963,1999,1879
   }
		
   private function removeDuplicates(array:Array):Array{
      for (var i:uint = array.length; i > 0; i--){
         if (array.indexOf(array[i-1]) != i-1){
            array.splice(i-1,1);
         }
      }
			
      return array;
      }
   }
}

Pretty simple really. All that's happening is that we loop backwards through the array we pass into the removeDuplicates function. While we move backwards through the array, we use indexOf to find the chronological value at i, and thus if any values found at the end of the array match elsewhere in the array but the indexes don't, the one at the end of the array gets pulled or "spliced" from the array. If you think about it, it makes sense.

I'm pretty sure someone will find a need for this. Hope it helps.

Using AMFPHP Is Not As Difficult As It Seems

Sat Mar 6 02:43:56 2010

AMFPHP is great if you want to connect to a database, mainly because the data you send is converted to binary making it's probably the fastest way to get your data from A to B. Below is a simplified explanation of how to get connected and I have included a simple class to conveniently call a connection anytime you want to send or receive data.

First of all, you will have to go to the AMFPHP Webpage and download the necessary files. (There should be a download link on the top left of the webpage). Once downloaded and unzipped, I generally change the name of the folder to 'amfphp' (if it's not already) as the version number that sometimes gets added to the name can be a little hard to remember, especially if you are working with multiple servers. However, if you think you can remember it, then you don't have to change anything. It's just something I do. You will, however, have to put this folder on your server. For this example, I will be assuming you have placed it on the root of your server, so in other words "http://yourdomain.com/amfphp".

Next up, click here to download my AMFConnect files. Included in this folder is a file called TestService.php. You will need to upload this file to the 'services' folder inside the amfphp folder you uploaded earlier. If you then go to "http://yourdomain.com/amfphp/browser/index.html you will confronted with the AMFPHP service browser where you can see all your goodies in one place. Find the TestService in the list on the left and click it. You will see a description of the testFunction that the class TestService contains. Below is a 'Call' button. Clicking will call the function testFunction and you should see "Function is working" displayed in the output window at the bottom. Any services you write in the future can be tested in this window.

Writing a AMFPHP Service

The following class is an example of a simple service that can be used with AMFPHP. You can use it as a template for other services you write simply changing the word MyService to the name of the file, and changing the function myFunction to any name you want. You can have as many functions in a service as you like, all of which will be viewable in the AMFPHP service browser talked about earlier.

<?php
class MyService {	
   /**
   @desc Write your description here
   */
   function myFunction(){
      return "Hello World";
   }
}?>

Connecting ActionScript to a Service

In ActionScript, all we really need to do to connect to AMFPHP is the following few lines of code.

var netConnection:NetConnection = new NetConnection();
netConnection.connect("http://localhost/amfphp/gateway.php");
netConnection.call("MyService.myFunction",new Responder(onRead, onFault), sendData);

On line 1 we create a NetConnection, which will allow us to connect with the world outside of the swf file that will be created upon compilation. We then pass the url of the place we want to connect to using the connect(url) method of NetConnection shown on line 2. Finally, on line 3 we use the call() method to initialize the connection passing in a few parameters.

Before I continue to explain what parameters go where, it's important to know that NetConnection can be used for a number of purposes and the following explanation is specific to connecting to AMFPHP.

Continuing on, to connect using the call() you have to pass in the name of the class and method you want to call in the form of a string. As show in the example, we can call "myService.myFunction". So if we want to connect to the TestService we uploaded and call it's testFunction, we would pass "TestService.testFunction". Next we have to pass in a Responder. As the name suggests, this will respond to our call and tell us whether is was successful or not. You can create a responder in a separate variable, but I have chosen to pass it directly into the call method for simplicity's sake. The responder will need to receive two functions. The first function it receives will be called on a successful connection to AMFPHP, and vice versus, the second will be called on a failed connection. Most people call these function onRead and onFault. In the example, theses functions have not been created, but I'm sure that if you are reading this, you will know how to do that. Alternatively, you could pass in two inline functions like this:

new Responder(function():void{/*do this on success*/}, function():void{/*do this on fault*/})

Finally, the last parameter that we can pass in is data to be sent. I generally like to pass an Object or an Array because you can send multiple sets of data in one call and easily retrieve them in the PHP files. That being say, you could simple send as little as a String or a Number. I suppose that depends on what you want to do.

Connecting the Easy Way Using My AMFConnect Class

I have to say that this is a toned version of a similar class that I created for personal use for all my connections. Admittedly, I don't feel comfortable sharing all that hard work and plus I think it helps your own understanding to be forced to create some of this stuff for yourself. But I would like to give you a big push in the right direction, so I have included a convenience class to get you more than started.

Inside the AMFConnect folder you downloaded earlier is a class called AMFConnect to do all the connection work for you. Simply change the url inside the connect call to the location of your amfphp folder on your server. The class requires two arguments. The first is the class and function you want to call in the form of a string. The second is data to be sent. To use it, first import AMFConnect and then call the following method.

var sendObj:Object = { data : "Send Data" };
AMFConnect.connect("TestService.testFunction", sendObj); 
// traces Send Data:Received Successfully
If you don't pass sendObj, the NetConnection will not send any data
MFConnect.connect("TestService.testFunction");
// traces Function is working

So there you have it. It's pretty easy to send a receive data using AMFPHP. If you are having trouble, you may need to look around for information on crossdomain.xml, which I won't go into here but should solve the majority of your problems. Anyway, for those just starting out in this area, I hope this has helped.

SharedObject - Flash Cookies

Tue Feb 16 06:04:06 2010

For anyone making applications using ActionScript 3.0, SharedObject is an absolute must! It allows data to be stored inside the flash player itself, meaning applications you create do not have to reply on browser cookies, and thus there is no worry of browser cookies being deleted or the hassle of writing a program in something like PHP to store your data on a database for example... although that may be a little more efficient especially if you are writing something that stores long-term data.

To use SharedObject, all you have to do is create a variable and datatype it to SharedObject. Don't forget to import flash.net.SharedObject if you haven't already. Take at the variable below.

var myData:SharedObject = SharedObject.getLocal("data"); 
By setting the SharedObject it will automatically be created by the Flash Player. There are no further steps involved in creating this data so it's quick and easy.

The SharedObject will accept all kinds of data including numbers, strings, arrays, etc. When data is not already set inside your SharedObject, it will return undefined. For example, I have yet to set any data in the variable 'myData' that I created earlier and so if I tried to trace any data I would get undefined.

trace("My data : "+myData.data.mySetData); //traces My data : undefined 
If I were now to actually set data and then trace it, SharedObject would return that data back to me.

myData.data.mySetData = "I set this."; 
trace("My data : "+myData.data.mySetData); //traces My data : I set this

Additionally, you can clear any data set by calling the clear() method on your variable.

myData.clear();
trace("My data : "+myData.data.mySetData); //traces My data : undefined

Naturally, that is not all there is to know about SharedObject, but it should be enough to get those who are not yet savvy about this on their feet. As a side note, this has been around for quite sometime and those game creators who haven't yet checked this out should definitely do so.

Use the Flex Framework with the Least MXML Possible

Mon Feb 15 00:54:09 2010

Using the Flex Framework is great tool to have if you know what you're doing. Sadly, not everyone has the time to put in the extra man hours to learn it, although I would thoroughly recommend trying to do so if you had the chance, as it can speed up your workflow immensely and there are so many pre-made components out there that you are really spoiled for choice.

In any regard, this post is mainly for those people who want to know how they can import components such as the ComboBox, Button, and the infamous DataGrid, and all with the minimum amount of MXML possible. However, I would just like to say before I go any further that it is probably a lot faster and easier in most cases just to learn that little bit of MXML than by doing it all in ActionScript alone... and believe me, being a big ActionScript fan, I was one of the ones who just didn't want to let go either. Anyhow, with all that said, let's get coding.

To my current knowledge, there are a few ways of getting this to work. In this post I will run through what I think is the best way of doing it. First off, you will need to create an MXML file. All files after this one can be ActionScript files, but the main project file must be a MXML file. Inside that file, you will need to place the following code.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
xmlns:classLocation="*">
	
	<classLocation:myClassName/>

</mx:Application>
I have set the layout to absolute since this will enable you to put your objects anywhere on the screen. Note that there are two more properties that you can play with; vertical and horizontal, which I won't go into now, but Flash coders for example will probably feel most at home with absolute layout.

The important thing to remember for this file is that when importing you own classes, you have to set the location so that flex can find it. I have used xmlns:classLocation="*", the * [hash] of which simply denotes 'root level', or the place where the MXML file exists. Alot of flex coders put their custom classes or components inside a folder called components and so they would use xmlns:classLocation="components.*". Finally on line 5 we call out custom class/component using classLocation:myClassName/>. The actual class name is determined in place of 'myClassName'.

Next create an ActionScript file as you would normally. The code below can be used for quick reference.

package{	
   import mx.core.*;
   import mx.controls.*;	

   public class Main {

      public function Main(){
		
         var app:Object = FlexGlobals.topLevelApplication;
         var l:Label = new Label();
         app.addChild(l);
         l.text = "Minimum MXML";

      }
   }
}
The code above simply places a label on the stage and sets the text to "Minimum MXML". The important thing to remember here is that in most cases you will need to set a reference to the FlexGlobals.toplevelapplication in order to add things to the display list, which is something I discovered recently after the move from Flex 3 to the Flex 4 SDK. On line 9 of the code above, I have created a variable called app, datatyped it to an Object and set it to FlexGlobals.toplevelapplication. Now each time I add something to the stage, I use app as a reference as seen on line 11.

And that's it. Compile the MXML file and you should see the words "Minimum MXML". If you aren't sure on how to compile MXML and ActionScript, take a look at one of my previous posts Compile AS files with Flex SDK

If you would like to download the example files for this post, you can get them from the link below.

Download Minimum MXML files

**Remember though, I do recommend learning a little MXML if that's why you are looking for this information. Don't fight it! You know that you want it really.

Migrating From FLEX 3 to FLEX 4: FlexGlobals.topLevelApplica

Sun Feb 7 04:16:48 2010

Today I cam across an interesting problem while working with the new Flex 4 SDK. I kept getting the following error.

Warning: 'application' has been deprecated since 4.0.  
Please use 'FlexGlobals.topLevelApplication'.

Naturally, I had no idea what this meant until I did a little research. Apparently, an application runs in its own ApplicationDomain which in turn has it's own topLevelApplication. Thus, you have to set the correct reference to the constructor of said top level application in order to get rid of the warning.

Replace this...
var mxmlApp:Application = Application(Application.application);
with this...
var mxmlApp:Object = FlexGlobals.topLevelApplication;
...and the sun will shine once more.

Easy ActionScript Chain Events

Fri Feb 5 15:19:45 2010

Ok, so this week I have been playing around with events and building all kinds of useless applications... and all while trying to further my education in the Flex Framework and Papervision 3D, which is all going ever so slowly. However, something interesting came from all my futility when I created a class that would pass multiple EventListeners together in a single sentence, giving you something that resembles the functionality of jQuery, albeit a lot less advanced. Allow me to explain...

FIrst of all, this class requires instantiation. Therefore, you will need the following import statement and the call for instantiation.

import Bind;
private var bind:Bind = new Bind();

Ok, so now that we have our Bind class ready, next we need something to test it on. Let's make a quick button.

var btn:MovieClip = new MovieClip();
btn.graphics.lineStyle(2, 0xffffff, .5);
btn.graphics.beginFill(0xCCCCCC);
btn.graphics.drawRoundRect(0,0,100,30, 10);
btn.graphics..endFill();
addChild(btn);
btn.mouseChildren = false;

var btnTxt:TextField = new TextField();
btnTxt.text = "Button";
var format:TextFormat = new TextFormat("Courier", 16, 0x333333);
btnTxt.autoSize = TextFieldAutoSize.LEFT;
btnTxt.setTextFormat(format);
btn.addChild(btnTxt);
btnTxt.x = btn.width/2-btnTxt.width/2;
btnTxt.y = btn.height/2-btnTxt.height/2;
btn.x = btn.y = 10;

Nothing special so far. Basically, all this code does is makes a slightly rounded rectangle and puts some text in it with the label 'Button'. We also set a TextFormat to set the style of the text and move the entire button 10px from top and left of the screen, just so we can see it properly.

Now, if we call the following code, the button will come to life.

bind.bind(btn,{over:overHandler, out:outHandler, click:clickHanlder});

private function overHandler(event:MouseEvent):void{
   //do something
}

private function outHandler(event:MouseEvent):void{
   //do something
}

private function clickHandler(event:MouseEvent):void{
   // do something
}

Ordinarily you would write this...
btn.addEventListener(MouseEvent.CLICK, clickHandler);
btn.addEventListener(MouseEvent.MOUSE_OVER, overHandler);
btn.addEventListener(MouseEvent.MOUSE_OUT, outHandler);
instead of this...
bind.bind(btn,{over:overHandler, out:outHandler, click:clickHanlder});

Quick example

The following example simply shows that in one line of code, you can add a remove multiple listeners from an object. Get Adobe Flash player

As you may see, the bind method allows you to string together Events and MouseEvents in one single sentence in the form of an object. Other parameters include "down" (MOUSE_DOWN"), "up" (MOUSE_UP), "move" (MOUSE_MOVE), "doubleClick (DOUBLE_CLICK), added (ADDED_TO_STAGE), enterFrame (ENTER_FRAME).

In addition to the bind method. there is an unbind method. If bind works the same as addEventListener, then unbind would be it's removeEventListener. In fact, not too surprising is the fact that both methods call add/removeEventListener.

I will try to update this class if I feel it is worth continuing, in which I case will write the version alongside the download below. It is currently version 1.0. If that is a different number to the one shown on the download link, then you will know I have updated it. On the other hand, I may never update it. In either case, I hope you enjoy it. I really don't expect you to use it in the place of addEventListener, but it should be good educational material.

Anyway, that's all for now, so get downloading it and see what you think.

Download Bind.as (Version 1.0) Class here

Update to Clock Class

Tue Jan 26 08:57:45 2010

Get Adobe Flash player

This is just to let you know that I have updated the DigitalClock class that I posted a little while back. The class is now called simply Clock.as. New functions include clockAnalogue() and clockDigital(). Just take a look below to see how to use them.


import Clock;

var clockAnalogue:Clock = new Clock();
var clockDigital:Clock = new Clock();

clockAnalogue.tickAnalogue(hourhand, minuteHand, secondHand, true);
clockDigital.tickDigital(textField, textFormat, true);

In the above code, we first import the Clock class and make two instances of it. One called clockAnalogue and the other clockDigital. These names can be anything you like.

Next we call the tickAnalogue function on the clockAnalogue instance. On the instance clockDigital, we call the tickDigital method. tickAnalogue and tickDigital tell the clock class whether it will be an Analogue or Digital style clock.

tickAnalogue takes four parameters, the first 3 are mandatory MovieClips and the last parameter is optional. The first paremeter represents the hour hand, the second the minute hand, and the third represents the seconds Hand. You can draw these just in code or create them in Flash, and then just pass them in.
The fourth and final parementer is just a Boolean. Setting it to true gives you GMT time. false gives you local time.

The tickDigital method takes 3 paremeters. The last of which is a Boolean and sets GMT or local time in the same way that it does in the tickAnalogue method. The first parameter takes the TextField that will display the time. The second takes a TextFormat to style the time.

..and that's it folks. Again, I hope you find this useful.

Download the Clock.as Class here

ActionScript 3 Digital Clock Class

Thu Jan 21 04:10:47 2010

Something as simple as putting the time on your site shouldn't be a difficult task and so I thought I would share a quick class with you that when instantiated creates and Textfield and tells the current time.

Here's the code.

import DigitalClock;

var clock:DigitalClock = new DigitalClock();
var clockGMT:DigitalClock = new DigitalClock(true);

addChild(clock);
addChild(clockGMT);
clock.x = 10;
clockGMT.x = 100;
	

Here's the result

Get Adobe Flash player

In the example above, we import and make two instances of the class DigitalClock. I have named them 'clock' and 'clockGMT' for obvious reasons.

You will noticed that we pass the Boolean true to the clockGMT instantiation to create a clock that displays Greenwich Mean Time (GMT) which is the local time in the UK. If you don't pass true or false the class will default to the local time (false) of the computer viewing it.

After that, all that's left is to add the clocks to the display list using addChild() passing in the name of each instantiation. I have also set the x position of the clocks so they don't appear on top of one another.

Download the DigitalClock Class here

Loading Fonts at Runtime

Tue Jan 5 09:53:51 2010

One of the painstaking things about creating swf files is embedding large font files which often end up bloating your flash movies and causing long wait times for your users. But what if I told you that there is a way to load fonts at runtime? Well, there is and it just so happens that I have prepared an example to guide you through it, allowing you the peace of mind that you can easily import the fonts you need when you need them and create subsets of them when every character in a font set is not necessary, and thus giving you a lot of power indeed.

Creating a SWF Contained Font

First off, you need to create a swf file containing the font that you wish to load into your movies. The big advantage to this is that you can have a library of preprepared swf files containing all your favourite fonts to load when and where you want. To understand how this is done, take a look at the following code.

package
{	
   import flash.display.Sprite;
   import flash.text.Font;
	
   public class FontEmbed extends Sprite{
      [Embed(systemFont='OCR A Std', fontName="OCR", 
      mimeType="application/x-font", unicodeRange="U+0041-U+005A")]

      public var ocr:Class;

      public function FontEmbed(){
         Font.registerFont(ocr);
      }
   }
}

On lines 7-8, we simply embed whatever font we want to be contained inside the swf file that is to be output on compilation of this class. In this example, I have chosen the font OCR A Std because it is a rather unusual font and will stand out against default fonts when testing to see if the font was actually embedded correctly. To embed your own font, simply change the systemFont string to the name of a font on your system if you don't have OCR A Std, which is highly likely if you are not on a Machintosh. The fontName can be any name you choose to remember this font by. This is important because we will be using this name to load in the font later. In my example, I have chosen the name "OCR" for simplicity. The mimeType is not something to worry about as it simply tells the Flex SDK what type of file to expect. Finally, the real power comes with the use of unicodeRange, which allows you to determine a range of characters you wish to embed. In this case, I have chosen the range U+0041-U+005A which is simply Unicode for A-Z.

There is a great little list of Unicode values to be found here at Wikipedia. Also, if you are running a mac, you could simply open a program such as TextEdit and go to Edit > Special Characters and roll over the characters to display their Unicode values. I'm sure Windows has something similar but don't quote me on that.

Continuing on, any font embedded must be datatyped to a Class, which is what the code on line 10 does. Finally, inside the constructor function on line 13, we register the font using Font.registerFont. Don't forget that to access any method of the Font class, you must import flash.text.Font (see line 4).

Once all that is done, simply compile the class to create the swf file containing your prefered font. As nothing has been added to the display list, nothing will be visible if you choose to view the swf file at this point.

Loading the Contained Font

Loading fonts is pretty simple. Take a look at the following code.

package
{	
   import flash.display.*;
   import flash.events.Event;
   import flash.text.TextField;
   import flash.text.TextFormat;
   import flash.text.TextFieldAutoSize;
   import flash.net.URLRequest;
	
   public class FontLoading extends MovieClip{
      private var ldr:Loader = new Loader();
      private var txt:TextField = new TextField();

      public function FontLoading()
      {
         ldr.contentLoaderInfo.addEventListener(Event.INIT, loaded)	
         ldr.load(new URLRequest("FontEmbed.swf"));
      }
		
      private function loaded(event:Event):void{
	 addChild(txt);
	 txt.autoSize = TextFieldAutoSize.LEFT;
	 txt.embedFonts = true;
	 txt.defaultTextFormat = new TextFormat("OCR", 22, 0x333333);
	 txt.text = "THIS FONT WAS LOADED AT RUNTIME";
      }

   }
}

On line 11 I have instantiated a Loader called "ldr", which will be used to load the font. The TextField on line 12 will only be used to display the results and is not necessary to load the font itself. On line 16, we add an EventListener to listen for the INIT event which basically means it will be waiting for the load to begin. Once it does, it will call the loaded function on line 20. The loaded function will add the TextField txt to the display list and auto-size it to fit the text on line 22. On line 23, we tell flash to use Embed fonts if it finds any (it should find our font) using txt.embedFonts = true. On line 24, we set the defaultTextFormat font on the TextField "txt" to "OCR". This is the name of the font we set when we compiled the swf containing our font, and this is how the Flex SDK will know which font we would like to use. On the same line, we set the font-size to 22 and the colour to a dark grey (0x333333). Finally on line 25, we give the TextField some text. All that is left is to compile the class and marvel at the wonder of loading fonts at runtime... a truly beautiful thing.

Download Runtime Font Files Here

Traverse Class - Useful Utility

Tue Dec 29 05:49:39 2009

How often have you had to make a photo gallery or something else that requires an index to be traversed? I know that I have come across this a lot and quite honestly I am tired I rewriting the same code over and over again. Thus, I've finally forced myself to write a class that will traverse an index and easily allow the assignment of objects that control the incrementation/decremental of said index... and I just thought I would share it with whoever is interested.

It's actually more of a helper/convenience class than anything. But I know I will personally be using it a lot in the future. The example below shows two arrows linked to an index displayed in a textfield. Click the arrows to see what I mean.

What It Does

Get Adobe Flash player

Code Example

import Traverser;
Traverser.init(MovieClip, "inc/dec", limit, callback);

How to Use This Class

Simply import the class as in the code example and then initiate the class using the Traverser.init() call. This class requires no instantiation. The first parameter labelled MovieClip should received the MovieClip that is to act as a button, like the two arrows in the swf example above.

The second parameter is a String where "inc" makes the MovieClip passed in the first parameter increment the index of the Traverser class, and as you would imagine, "dec" makes the MovieClip passed decrement the index.

The limit parameter determines the maximum limit the index will increment to before the index returns to zero. The limit of swf example is 5, and therefore the textfield will never display a number higher than 5.

Finally, the callback parameter will allow a call to a separate function once the index has been incremented or decremented. For those who are interested, in a way, the callback functionality is like a call to dispatchEvent(new Event()) calling a public static const, although all it really does is calls the function passed from inside the Traverser class. I thought this would work better than the alternative as I am using the Singleton approach and this is because I didn't feel the need to instantiate for as little as an index number, which is essentially what we are dealing with. Anyway, in the swf example above, I am using the callback function to update the TextField and give it a TextFormat. Without the callback to update the TextField, the TextField would not display any changes to the index.

Also, the index is contained inside a public variable and so can be access via Traverser.index to pull the current value. Again I didn't feel the need for getters and setters in this case, but if that's what you would prefer, feel free to update the code.

Download the files from the link below for a closer look at an example and for the code behind the arrow buttons.

Download the Traverse Class Here

Happy traversing!

Shorthand 'if else' Statement (ternary)

Sat Dec 26 04:15:23 2009

There's a lot to be learnt from simple reviewing the basics of programming on occasion, as my recent experiences have shown. Today, I would like to share a little shorthand 'conditional statement' with you that I've picked up along the way, which may help from time to time in your own coding.

As you may already know, the most commonly seen conditional statement syntax in ActionScript 3.0 is as follows:

Example 1

var sayHello:Boolean = false;

if(sayHello == true){
   trace("hello");
}else if(sayHello == false){
   trace("goodbye");
} 

//traces("goodbye");

This can be shorted to a single line in most, if not all programming languages to something like the following:

(checkstatement)? doSomething() : doSomethingElse();

So if you wanted to do the same thing as the if statement in Example 1 above, you might do this:

var sayHello:Boolean = false;

(sayHello)? trace("hello") : trace("goodbye"); //traces goodbye

sayHello = true;

(sayHello)? trace("hello") : trace("goodbye"); //traces hello		

In actual fact, I have to confess that this is something that I have learnt from my endeavours into the world of PHP, but its use is far wider and I'm sure that it will help make your coding a little bit tidier and easier to read. If anyone discovers any limitations to either way, I would love to hear about them.

Compile AS files with Flex SDK

Thu Dec 17 00:35:34 2009

At the time I began learning ActionScript in Flash, which is probably where most of us start, Flex was not something I even considered. At that time, the timeline looked all too comfortable and compiling from classes alone simply looked like far too much hard work. However, all that has changed now and as I wrote in one of my earlier posts, with the use of SVG and FXG(Flex 4),the albeit wonderful drawing tools of Flash are no longer necessary. So with that said, there are no excuses not to try it out.

Before you attempt anything though, get over to Adobe Open Source and download yourself the Flex SDK and save it somewhere you can get your hands on it easily. I'm currently using Flex 4 (Gumbo), which is at the beta stage at the time of writing this post. Those who like stability should grab the latest Flex 3 version. Either will suffice for our purposes.

Once your download has finished and has been unzipped, you should have a folder called flex_sdk_3 or flex_sdk_4, depending on which version you downloaded. Inside this folder, you should find a folder called 'bin' inside of which you will find a file called 'fcsh'. The file 'fcsh' is the Flex Compiler Shell and will be used to compile our classes.

The other thing you are going to need is a file to compile. For your convenience, here is some code that will get you a little 'Hello World' project going. Just save it as Main.as

package
{
   import flash.display.*;
   import flash.text.*;
	
   public class Main extends MovieClip
   {
      	private var txt:TextField = new TextField();
	private var txtFormat: TextFormat = new TextFormat( "Helvetica", 22, 0x333333);
		
      	public function Main()
      	{
		addChild(txt);
		txt.selectable = false;	
		txt.autoSize = TextFieldAutoSize.LEFT;
		txt.text = "Hello World";
		txt.setTextFormat( txtFormat );
		txt.x = stage.stageWidth/2 - txt.width/2;
		txt.y = stage.stageHeight/2 - txt.height/2;
      }
   }
}
Compiling using Flex Compiler Shell (fcsh) in OSX

Compiling using Terminal is very easy. First open it up. If you have never used Terminal before, you'll probably find it inside the Utilities folder inside your Applications folder. Once Terminal is open, we need to use it to open up the Flex Compiler Shell. There are three ways to do this on Mac. You could type the location of the fcsh file into Terminal and press Enter. You could drag and drop the fcsh file into the Terminal window and press Enter, or you could just double click the fcsh file.

Compiling using Flex Compiler Shell (fcsh) in Windows

Compiling in Windows is virtually the same process to that of a Mac. The only real difference is that you use Command Prompt instead of Terminal and you open the fcsh jar launcher instead of the fcsh unix executable file.

Whichever way of you choose on whatever OS you use, you should be faced with a Terminal/Command Prompt window that displays the following on it's last line.

(fcsh)

If for some reason, you cannot open the fcsh or are not greeted with (fcsh) in Terminal, go get another build. Chances are that another build will work out for you.

If you do see the (fcsh) message, compiling from here is easy. Type the following code and press Enter.

mxmlc -o="The location you want to output to" -file-specs="The localation of you class"

If your Main.as file is on your desktop on OSX and you want to save the swf to the same location, the line above will look like this.

mxmlc -o=/Users/YourName/Desktop/Main.swf -file-specs=/Users/YourName/Desktop/Main.as

Instead of typing the full location, something I sometimes do is type mxmlc -o= and the drag the file I want to compile into the Terminal windows and then change the '.as' to '.swf' and then continue typing, again dragging the class file into the Terminal window after the -file-specs part.

Provided everything was fine with your class, you should now see a .swf file in the output location you entered. If you open that up, you should be greeted with the words "Hello World". Congratulations! It's not really that hard and the advantage to compiling using fcsh as opposed to other methods available is that it shaves a lot of time of the each compile. As long as you don't close the Terminal window, what you compiled previously will still be in the compiler memory and it will simply recompile any changes to your files rather than recompiling the whole thing.

In my opinion, this is a great free alternative to any of the paid software out there. Anyone who hasn't should definitely check this out. For choice of good editors, FlashDevelop (free) seems to be most peoples choice of free editors on Windows, and I personally am a big TextMate (paid) fan and thoroughly recommend it for all types of coding on OSX. As a side note, compiling can be done from inside either of these editors which makes life a lot easier too.

Parsing XML with AS3 and E4X

Thu Dec 3 04:27:03 2009

Compared to AS2 parsing XML in ActionScript 3 is a dream, since it uses E4X (ECMAScript for XML) which is a programming language extension that gives AS3 native support for XML. Once an XML file is loaded, pulling specific data out of the returned xml data is a sinch. Also, I've added a bonus class that will make parsing XML even easier. You don't want to miss this one.

First off, take a look at this.

package
{	
   import flash.display.*;
   import flash.events.*;
   import flash.net.*;

   public class NormalParsing extends MovieClip
   {
      private var ldr:URLLoader = new URLLoader();
      private var xml:XML;
      private var xmlList:XMLList;

      public function NormalParsing()
      {
         ldr.load(new URLRequest("bin/data.xml"));
         ldr.addEventListener(Event.COMPLETE, loaded);
      }

      private function loaded(event:Event):void{
         xml = XML(event.target.data);
         xmlList = xml.children();

         trace("*************** XML ***************n"+xml);
         trace("*************** XMLList ***************n"+xmlList);
      }

   }
}

The above code is all the code you need to load a xml file using ActionScript. Here's how it works. First we create a new URLLoader instance on line 9 and inside the constructor function we load a new URLRequest passing in the string "bin/data/xml", which is the location of our XML file (lines 15). We add an EventListener (line 16) to the loader and listen for the COMPLETE event which will call the loaded function on line 19 once the XML file has been fully loaded. The XML file itself may only take a few milliseconds to load but trying to access any properties or functions that involve the information being loaded before the information is fully available will more often than not cause errors of doom, so make sure that you add the listener and wait for the load to complete. Finally, with all the data loaded we put the XML data returned into the xml variable defined on line 20 and the children of the XML (xml.children()), which is another way of talking about the XMLList, inside the xmlList variable define on line 21.
After that, the information can then be accessed from inside those two variables as the trace statements at the end of the loaded function prove.

The structure of the XML is the same as the XML file used in the jQuery XML parsing example in a previous post. There is a list tag, inside of which are a few item tags including an 'id' attribute. Each item tag holds a head and url tag. So how do we access this information specifically. The answer is simple. We use E4X.

For example, if we wanted to access the 'id' attribute from the xml variable, we would use the following syntax.

xml[n].attribute("attribute name");

The number written in place of 'n' represents the position inside the XML and this always starts at 0. Therefore, if we wrote xml.item[0].attribute('id'); inside of a trace statement, the first 'id' attribute value would be returned, which in this case is "1"; If we wrote xml.item[2].attribute('id');, the attribute value "3" would be returned.

To access the head tags in the XML, we would use the following syntax.

xml.item[0].head //returns CuluCulu Flash
xml.item[3].head //returns Gakushu Support Juku

To return the url tag we would use the following syntax.

xml.item[0].url //returns http://www.culu-culu.com/culuculu/flash
xml.item[3].url //returns http://www.supportjuku.com

Parsing XMLList data is done in a very similar way, but this time we will be replacing xml.list[n] with xmlList[n]. Also, to access the 'id' attribute in the XMLList you would use an @ mark instead of the word 'attribute' as was the case when accessing attributes in XML data. For example:

xmlList[2].url //returns http://www.supportjuku.com
xmlList[0].@id) //returns 1 

As you can see, E4X is a very powerful tool and is one that will take your coding leaps and bounds.
To finish off though, I would like to introduce you to a quick class I whipped up that uses a public static function to parse XML data, meaning that it doesn't require instantiation. You can download my XMLParsing class here.

It's implementation is very straight forward. Simply import the class using the statement import XMLParsing and then use the remote method to pass in the url to your XML file, and finally add an EventListener to listen for the complete call. Example code is as follows.

import XMLParsing;
XMLParsing.remote("data.xml");
XMLParsing.addEventListener(Event.COMPLETE, init);

function init(event:Event):void{
   trace(XMLParsing.xml);
   trace(XMLParsing.xmlList);
}

As you can see from the code above, you can access the xml and xmlList variables to access whatever data you want. When working on big projects, however, it might be a good idea to store these variables inside variables of the class importing the XMLParsing class, as a new remote call will change the data stored in the XMLParsing class. So, there you go. I think some of you may find it useful. Let me know how you get on. All files for this post can be download here

AS3 Simple Grids

Sat Nov 14 16:16:16 2009

I have decided to share a class with you that I recently developed for an ActionScript project that required a grid layout of MovieClips. Making grids in AS3 isn't really that difficult, but the class I've developed will save me a lot of typing and since building grid layouts is something that I may do a lot more of in future projects it seemed like a sensible thing to do.

It is quite a simple class but may come in handy from time to time. Please feel free to edit the code and do as you will. It's usage is simple. Just import it, create however many instances of an object you want to have in your grid, and apply the public static function createGrid(); from the Grid class. In the example grid below I used dark grey, 40 x 40 px MovieClips

Get Adobe Flash player

Grid.createGrid(); The parameters are (1:StageObject, 2:Array, 3:{Object})

Instructions of Use

1. The StageObject is simple. Just pass the stage of the first MovieClip your are throwing inside the grid. This will give us the ability to call the public static method without instancing the class itself, which I always find beneficial and try to do when I can.

2. The Array should be an array of all the names of the objects you want to place inside the grid. Objects will be ordered in the same order as they are placed inside this Array.

3. The Object can contain any of the 4 options available, which include col, spaceX, spaceY, and centered. col receives a Number and defines the number of columns the grid should have. spaceX and spaceY also receive a Number and respectively control the vertical and horizontal spacing between each object inside the grid. In other words, they control how big the gaps are inside the grid. The final parameter center:Boolean gives the option to offset the grid to the right by half the width of each instance fed into the array, so that the grid appears centered. If no parameters are given (Note* curly brackets are required {} even without parameters), the grid will set to a default of a non-centered, 6-columns grid with 10px vertical and horizontal spacing

Example Code

Grid.createGrid(this, nameArr, {cols:10, spaceX:10, spaceY:10, centered:false} );

For more info, just take a look at the fully annotated example files I've set up. They can be downloaded here

I would love to hear your opinions about this, but since I don't normally share my code, please be gentle with any criticisms. If you would like to host this code on your own website, please make sure to credit back to yours truly. Happy grid making!

The Scope of Things

Wed Oct 14 02:20:48 2009

Sometimes it can be a little difficult to get the specific "child" you want in ActionScript 3 by calling its name directly. Also, the use of getChildAt() and getChildByName("") doesn't work because they are outside the scope of the current class in question. Well, this is where you could try casting.

For example, say that I have three classes. One called Main.as, one called Second.as and one called Third.as, each containing a single MovieClip containing a Square, Circle and Triangle respectively. Main imports Second and and Third and so becomes their "parent". The result is a Square, Circle and Triangle on the stage.

Now say that I want to access Third from Second to change the scale or some other property of Third's triangle. Well, I would need to use the this.parent.getChildAt(position).getChildAt(position) or maybe this.parent.getChildByName("second).getChildByName("triangle"), that is, if I had given them names. However, this is where you would run into problems. Flex/Flash just doesn't know what you are talking about. Instead, by casting all instances and clips to "MovieClip" and holding them inside variables, you will ensure that Flex/Flash knows exactly what you want to access and what type of object it is.

Here's what I'm talking about

    //this.parent.getChildAt(1).getChildAt(0) just doesn't work. It's outside the scope
    //of the class called Third.

    var sec:MovieClip = MovieClip(this.parent.getChildAt(1));
    var tri:MovieClip = MovieClip(sec.getChildAt(0));
    tri.scaleX = 2; 

I know that some will complain that there is a better way to code and a good coder wouldn't code this way, and I would say I agree for the most part. However sometimes, whether it be a quick fix, or a quick add-on to an existing application coded by someone else, sometimes this will come in handy. After all, we can't guarantee the work of others.

If you would like a closer look, I have provided some fully annotated files here

FXG in ActionScript 3

Mon Oct 12 12:58:53 2009

With the introduction of the Flex 4 SDK (Gumbo), it is now possible to import FXG files into your ActionScript and MXML projects. In this example, I will be using an illustration of a flower, aptly named Flower.fxg which was created in and exported from Illustrator CS4.

I would also like to add that what I'm about to do is also possible using SVG files, and for anyone using TextMate or FlashDevelop, this looks a very promising replacement to the Flash IDE and library.

First, you need to create a package and embed your vector graphic as a Class. Embedding required the Flex SDK, so for Flash users who wish to try this out, you will need to get the Flex SDK and point flash in the right direction.

The finished article looks something like this:
package  {
      import flash.display.Sprite;
      import flash.events.MouseEvent;

      [SWF(width='500', height='500', backgroundColor='#FFFFFF', frameRate='60')]
	
      public class Main extends Sprite {
 	
	    [Embed(source='Flower.fxg')]
	    private var Flower:Class;
	    private var flower:Sprite = new Flower();
 
	    public function Main() {
	       addChild(flower).addEventListener(MouseEvent.CLICK, clickHandler);
	       flower.buttonMode = true;
	    }
		
	    private function clickHandler(event:MouseEvent):void {
	       trace("Flower Clicked");
            }
      }
}

After this class has been created, simply compile it making sure that the FXG file is where it's supposed to be. In my case, I used TextMate and the FLEX 4 SDK to compile. The result is as follows.

Get Adobe Flash player

Pretty cool stuff if you ask me. Anyway, for anyone interested, you can find the files for this here

Most recent posts

  1. Flashcards Maker - the app the helps you learn in a flash
  2. Convert Font Suitcase to TTF in 3 Easy Steps
  3. Rain or Shine - Weather Forecast Available Now!
  4. Getting around Apple's silly rules for iOS 10
  5. Localising App Names for iOS and Android

Search site:

Apps by Ubacoda.com

Click the app icons to see more info


Archives

Categories