Friday, December 22, 2006

Happy Holidays!

Well, this is going to be my last blog post of the year. I must say, this year has been fun and exciting. I've had the opportunity to work on some great projects, and have meet some great people. I'm a sucker for this time of year... Christmas is by far my favorite holiday. To celebrate the holiday season, I've put tgether a basic mp3 player with simple waveform visualization (in a Christmas theme). It's a very basic application. Nothing fancy at all, but it shows you the basics of playing a mp3 and using the ComputeSpectrum method (not to mention it celebrates the holidays). I hope you enjoy it, and Happy Holidays!



See you next year!
-Andy

andrew.trice[ at ]cynergysystems.com

View Application Standalone
View Source
Download Source
(sorry, I didn't attach the mp3 to the distributed source)

Monday, December 18, 2006

getters and setters vs. public properties in Flex

I've been asked several times, why would you use get/set functions instead of public variables in your flex components and classes? Well, there are some great things you can do with getters and setters that you can't do with public variables. On the other hand, there are cases where public variables work better. When using these functions and/or public variables, the code for the caller will be the same:

mycomponent.myValue = 1;


First, lets look at public variables...

[Bindable]
public var myValue : Number

It is better to use public variables when there are no addional actions that need to take place when the value has been changed. If you change the value of "myValue", the bindings will update and everything will be handled accordingly. The value will change, and anything bound to that value will change. In this case, there is no need to use getter/setter methods.

Now, on to getters and setters...

[Bindable(event="myValueUpdated")]
public function set myValue (value:Number):void
{
_myValue = value;
dispatchEvent( new FlexEvent( "myValueUpdated" ) );
}

public function get myValue ():Number
{
return _myValue ;
}

private var _myValue : Number;

First I'll explain the [Bindable(event="myValueUpdated")] statement: This indicates that the data binding to the getter's value should be updated when the event of type "myValueUpdated" is dispatched. You'll notice that when the value is set, this event is dispatched, which would notify and components that are bound to this value.

Now, the rest... The code that I showed above does not have any benefits over the public property, it functions in exactly the same way, but requires more code. The benefits of getter and setter functions is that they enable sequential code execution when the value is changed. You can create your components so that specific functions are executed any time that the value is accessed using get and/or set functions.

Here's an example:

[Bindable(event="myValueUpdated")]
public function set myValue (value:Number):void
{
_myValue = value;
numSets ++;
myFunction();
dispatchEvent( new FlexEvent( "myValueUpdated" ) );
}

public function get myValue ():Number
{
numGets ++;
myOtherFunction();
return _myValue ;
}

private var _myValue : Number;
private var numGets : Number = 0;
private var numSets : Number = 0;

In this example, every time the value is set, the numSets Number is incremented, and the myFunction() function is executed. Likewise, every time the value is accessed using the "get" method, the numGets Number is incremented, and the myOtherFunction() function is executed. There is no limit to what kind of code you can execute here. You can have it dispatch custom events, change styles, create new components, etc... This turns out to be very handy when creating custom Flex components.

I hope you find this helpful! Feel free to contact me with any questions/comments at andrew.trice[ at ]cynergysystems.com.


Object Orientation

Understanding of OOP (Object Oriented Programming) is fundamental in being successful with the Flex framework and being able to get the most out of it. People without a computer science-related (or similar) background may not know much of the fundamental concepts that comprise OOP and how to apply them correctly, so here is a quick piece to help you out...

First, object oriented programming is a programming paradigm where your code is organized into logical objects, and each object has properties and methods. Each object contains similar and/or related functionality, and is organized into classes that logically represent and logically organize it's functionality.

For Example:
Let's say that we have a class "Automobile". This class would contain the information and functions necessary for our application to use the automobile class. We could have a numeric property for the number of wheels, the speed, and the direction (degrees on a compass). This class would also contain methods that control the actions of the Automobile object: accellerate, decellerate(break), turn, start engine, stop engine, etc... Our class would look something like this...

public class Automobile
{
public var speed : Number;
public var direction : Number;
public var numWheels : Number;

public function Automobile()
{ /* constructor */ }

public function accellerate() : void
{ /* speed up the automobile */ }

public function decellerate() : void
{ /* slow down the automobile */ }

public function turn( direction : Number ) : void
{ /* turn the automobile */ }

public function startEngine() : void
{ /* start the automobile engine */ }

public function stopEngine() : void
{ /* stop the automobile engine */ }
}


Ok, now that we have a brief explanation of what object oriented programming is, we can get into some more aspects of OOP: inheritance and interfaces.

Inheritance is a way to form new objects based on existing objects. When a class inherits from a base class, the new class can utilize public and protected properties and methods from the base class. Inheritance can be used to create different objects that utilize functions within the base class, so that the child classes all utilize the same code base. Inheritance can be used to extend the functionality of existing objects, and inheritance can also be used to override and/ or change functionality from the base class.

In Actionscript 3, you can access the parent class of your class by using the "super" keyword. For instance, calling the constructor of the parent class would use "super()", where accessing a method of the parent class would use something like: "super.myMethodName()". If a property of the parent class is created with public or protected access, you can access that property in the child class directly by the property name (you would use this.propertyName, not super.propertyName).

Now, Lets take our automobile example and apply it to inheritance. We already have a base Automobile class that covers the basic functionality. We can create child classes that extend the functionality of the automobile.

public class SportsCar extends Automobile
{
public function SportsCar()
{
super();
}

override public function accellerate():void
{
/* we can override the accellerate function
so that it accellerates faster than the base
Automobile */

}
}


public class Truck extends Automobile
{
public function Truck()
{
super();
}

public function tow() : void
{
/* we can add a tow function that
allows the Automobile class to tow
items. */

}
}


These classes extend the base functionality of the Automobile class, and therefore are instances of the Automobile class. If we have a function outside of the Automobile class, which takes an automobile as the parameter, both a SportsCar and Truck will work since they are both Automobiles. We could have a function such as the following: If we pass in a Truck Instance, and a SportsCar instance, both will work, and each will use the functionality of their specific class instead of the base Automobile class.

public function race( auto1 : Automobile, auto2 : Automobile ) : void
{
auto1.accellearate();
auto2.accellearate();
}


I'll get into some more fine-grain details about inheritance later in this post... now, lets move on to interfaces...

Interfaces are slightly different than inheritance. An interface is a set of "rules" which an object must adhere to. The "rules" are actually method signatures and variable instances that your class (which implements the interface) must implement. When we define an interface, we define method signatures that are required for classes that implement the interface. There is no actual code in an interface; it simply defines methods that must exist within your class. Your class that implements the interface must implement the code for the actual function. If you have multiple classes that implement an interface, those classes must have the same functions (only the ones required to implement the interface), but that is where the similarities of the two classes may stop. They could have completely different logic and properties withiin them... this is where inheritance and interfaces differ. Two objects that inherit from the same base class have a lot in common (properties and methods): two objects that implement the same interface only have those interface method signatures in common.

Let's now make an Automobile Interface that defines the functions required to create an IAutomobile object (note the "I" stands for "interface"):

public interface IAutomobile
{
function accellerate() : void;
function decellerate() : void;
function turn( direction : Number ) : void;
}


We can use the IAutomobile interface to create objects (classes) that behave as Automobile objects. These classes do not necessarily inherit from each other and do not necessarily share any common properties.

public class Car implements IAutomobile
{
private var direction:Number;
private var speed:Number;

public function turn(direction:Number):void
{
this.direction = direction;
}

public function decellerate():void
{
this.speed++;
}

public function accellerate():void
{
this.speed--;
}
}


<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas implements="IAutomobile"
xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[

private var direction:Number;
private var speed:Number;

public function turn(direction:Number):void
{
this.direction = direction;
}

public function decellerate():void
{
this.speed++;
}

public function accellerate():void
{
this.speed--;
}
]]>
</mx:Script>
</mx:Canvas>


The previous two components both implement the IAutomobile interface, but have nothing else in common. One is simply a class that implements the interface, the other is a mxml component that implements the interface. The mxml component example extends the mx:Canvas component (the same thing could be done by creating an AS class that extends mx.containers.Canvas). Now, lets look at a function similar to the "race" function from earlier...

public function race( auto1 : IAutomobile, auto2 : IAutomobile ) : void
{
auto1.accellearate();
auto2.accellearate();
}


This example will work with either object that I have created because both objects implement the IAutomobile interface. The do not rely upon functions in the class hierarchy, just those that were implemented for this interface. You can also use multiple interfaces on classes that you create. Implementing multiple interfaces basically means that you are adding more required method signatures to your class, and you will have to implement these methods to satisfy each interface. On the other hand, you cannot inherit from multiple classes. Some programming languages allow for multiple inheritance... ActionScript 3 does not support multiple inheritance (so i'll stop there).

OK... enough of this rambling... What does this have to do with Flex?
Inheritance and interfaces are used extensively in AS3 to create the flex framework. Just look at the flex documentaiton for the mx:Canvas component, and you can see inheritance in action.

Canvas Container UIComponent FlexSprite Sprite DisplayObjectContainer InteractiveObject DisplayObject EventDispatcher Object

All flex framework components that are rendered to the screen extend from the UIComponent class. All combo boxes and lists implement the IList interface, an AbstractService, DataSerice or EventDispatcher object implements the IEventDispatcher Interface. You may be using these concepts every day, but weren't aware of it, and how you can use it to your own benefit. Inheritance seems easier to take advanatage of at first... Lets say that you want to create several objects, all of which will have identical functions and variables. It is easy to see that you can create a base class that encapsulates all of the common functionality. You can then create a sub-classes that implement the differing functionality for each class.

When putting these concepts into real-world Flex applications you'll need to get familiar with the following keywords:

extends
This is used when defining a child class from a parent class.
public class A extends public class B 


implements
This is used when implementing an interface.
public class MyClass implements MyInterface 


final
Classes and methods implented with "final" cannot be overridden.
final function myFunction() : void


static
This is used when creating variables or functions in a class that are specific to the class, not the instance. Static properties and methods do not require variable instantiation to be executed.
public static function myStaticFunction(): void 
//to use it call it directly from classMyClass.myStaticFunction()

internal
This is used when creating a method or property that can be accessed by any object within the same package (namespace)
internal var foo : String;


override
This is used when creating a function that overrides a function within a parent class.
override public function myFunction() : void 


private
This is used when creating methods or properties that are only availaibe to the class where it is defined. A private variable cannot be accessed by outside classes or from descendant classes.
private var myPrivateValue : String;


protected
This is used when creating methods or properties that are only availaibe to the class where it is defined and descendant classes. A protected variable cannot be accessed by outside classes.
protected var myProtectedValue : String;


public
This is used when creating properties and methods that are available to any class.
public var myPublicValue : String;


Feel free to contact me with any questions/comments at andrew.trice[ at ]cynergysystems.com



Friday, December 08, 2006

My Presentation On Skinning & Styling

Hello again! Here's my content and examples from Wednesday night's Flex User Group presentation, for those of you who couldn't be there. <joke>You had better be there next time</joke> I spoke about creating your own css styles, derived styles, image based skinning, scale9 grids, drawing API and programmatic skinning...

Here's my presentation: (although the fun stuff is really in the code examples)And here are my code examples:
  1. Here is my example for creating and using custom styles. It is very similar to an older blog post, but takes the concept a bit further. It shows you how to use css styles to define styles within subcomponents of your Flex components. It also shows how you can use custom css style definitions to set properties on your application, such as item height, button labels, etc...





  2. Here is my example for understanding scale9. This really just shows how to use scale9 when embedding assets as skins, and the effects that scale9 has on the skins of you applications.





  3. Here is my example for skinning with images. This shows you a few cool things that you can do using images to define buttons and backgrounds within your application. Of all my demos, I think this one is my favorite. Be sure to open a window using "The Trice Theme". :)





  4. Here is my example for the drawing API. It consists of 2 tabs: The first shows simply how to draw lines and curves. The second is a very basic paint-drawing application.




  5. My fifth example shows you how to draw a VERY basic programmatic skin. All this does is draw a colored rectangle for a button skin. It is meant to be ugly, but does a good job of showing you how to create a programmatic skin.





  6. My last example shows you how to draw an advanced programmatic skin. These skins are also based off of an earlier blog post and are modifications of the Flex halo skin theme. Examining the halo theme is a great place to learn the in's and out's of programmatic skinning. This example also shows you the effects of changing styles at runtime (which is an advantage to programmatic skinning).




Or, you can download everything here:Enjoy!

Feel Free to contact me with any questions at andrew.trice[ at ]cynergysystems.com.

Friday, December 01, 2006

An Interactive Map of Zelda...

This is just for fun... Someone posted on digg.com today about a map of the original Zelda game for the Nintendo. I decided to throw this into my image viewer to have a zoomable/pannable map. It's located here: http://www.tricedesigns.com/portfolio/zelda/mapviewer.html. Enjoy!

Realtime Thumbnails of Flex UIComponents

Here's an experiment that I have been toying with lately... I took the concepts from an older blog posting on Bitmap objects and applied it to an actual usable interface. It's not the prettiest application in the world, but its still pretty darn cool (in my opinion)... hence it is an "experiment". This example shows how to generate thumbnails of instantiated UIComponent objects in real time. So, every time that the UIComponent is updated, so is its thumbnail.

The thumbnail generation for this example uses the same function from my previous post:
private function getUIComponentBitmapData( target : UIComponent ) : BitmapData
{
var bd : BitmapData = new BitmapData( target.width, target.height );
var m : Matrix = new Matrix();
bd.draw( target, m );
return bd;
}
Basically, I created 4 different panel objects and 4 different states. In each state, one of the panels is "maximized" to fill the content area. On the top of the application, I have a mx:TileList control that will hold my thumbnails. On creationComplete of the application, I create an ArrayCollection for the dataProvider of the mx:TileList. In that ArrayCollection, I put refferences to the instantiated components. In the itemRender for the mx:TileList, I use the references to the instantiated components to generate thumbnails of the components using the getUIComponentBitmapData function. I use a timer in the main application to dispatch an "updateImage" event ever 500 milliseconds, which notifies the itemRenderer to update the thumbnails.

The first panel (red background) contains a mx:TextBox control. As you type in the textbox, you can see the top left thumbnail being updated. No, you can't read it when it is that small, but you can see the changes happening. :)

The second panel (green background) contains a mx:DateChooser component. As you select dates, or mouseover dates, you can see the changes reflected in the thumbnail image.

The third panel (blue background) starts getting a lot more interesting. This example uses code based off of actionscript.com's drawing example to have a basic paintbrush application. As you draw on the canvas, you can see the thumbnail getting updated with your changes.

The fourth panel (purple background) uses an actionscript "FireFly" effect, based on an AS3 example that Keun Lee modified and showed to me. I limited the # of pixels being set, and the maximum size to increase performance in this example. You can see that the thumbnail gets updated with the firefly image.

Click on the "play" button below to view a FLV video of a demonstration of this in action:



Click on the "play" button above to view a FLV video of a demonstration of this in action:


If you are having any performance issues with this example, it is related to the 4th panel (FireFlys)... This is very processor intensive. Download the code, comment that out, and you should see a huge improvement. Feel free to contact me with any questions/comments at andrew.trice[ at ]cynergysystems.com

Now, you might be wondering where this would actually have any practical application... The first thing that comes to my mind is a charting dashboard. You could have thumbnails of various charts, changing in real-time, based on real data. If you want to drill into a chart, you select it, and view the full-sized version of the chart. The second thing that comes to mind is image editing... Lets say you were creating a RIA-based version of a photo/image editor. You could give thumbnail previews of multiple open images, or you could use the thumbnails to show mini-versions of layers of the composition. There have to be a ton of useful applications for this, which are just waiting to be discovered.

Note: This code technique will currently only work with instantiated components. Components that are null/uninitialized will throw exceptions, which I haven't looked into yet.