How to use Static properties and methods to simplify your tasks in Flash

Do you write your code over and over every time you need to align an image to the stage center of your project? or maybe for some other task? I know I used to before I learned about static properties and methods, of course I had some snippets for that stored somewhere but still this is not the best solution.

This is very useful because it allows you to use properties from a class without having to import it first. Basically all you need to do is put the word static when declaring the properties and methods inside your class.

Utils.as

package
{	
	/**
	 *  Description
	 *    
	 *  @langversion ActionScript 3
	 *  @playerversion Flash 9.0.0
	 *
	 *  @author Pedro Canterini
	 *  @since  11.04.2009
	 */
 
	import flash.display.DisplayObject;
 
	public class Utils
	{
 
		public static var myStr:String = "My tring here...";
 
		/**
		 *   @constructor
		 */
		public function Utils()
		{
			//super();
		}
 
		//---------------------------------------
		// Align to center
		//---------------------------------------
		public static function alignToCenter(obj:DisplayObject):void
		{
			obj.x = obj.stage.stageWidth / 2 - obj.width / 2;
			obj.y = obj.stage.stageHeight / 2 - obj.height / 2;
		}
 
	}
}

How to use it:

Utils.alignToCenter(theDisplayObject);

Notice that you can align any display object to the center of the stage not just images.

  1. Min says:

    Some suggestions:

    1. Name the package and class more appropriately to fit into a complete library of your own. Maybe com.flashinit.utils package named PositionUtil

    2. Add functions for aligning left, right, center, top, bottom, middle. Then modify all of those functions to work with different registration points. Your code assumes the DisplayObject has a top left registration point.

    3. Create shortcut functions for each variation (e.g. alignTopCenter, alignTopLeft, alignTopRight, etc).

    4. Don’t forget to put this in your comments that this assumes that the DisplayObject is already added to the stage!

  1. CODY says:


    MedicamentSpot.com. Canadian Health&Care.Special Internet Prices.No prescription online pharmacy.Best quality drugs. High quality pills. Buy pills online

    Buy:Viagra Super Active+.Cialis Professional.Propecia.Viagra Soft Tabs.Cialis Soft Tabs.Zithromax.VPXL.Cialis Super Active+.Super Active ED Pack.Maxaman.Soma.Viagra.Tramadol.Viagra Super Force.Cialis.Levitra.Viagra Professional….

  2. SCOTT says:


    CheapTabletsOnline.Com. Canadian Health&Care.Special Internet Prices.Best quality drugs.No prescription online pharmacy. High quality pills. Buy drugs online

    Buy:Cialis Soft Tabs.Cialis.Viagra Super Active+.Viagra Soft Tabs.Tramadol.Zithromax.Levitra.Cialis Super Active+.VPXL.Maxaman.Viagra Professional.Super Active ED Pack.Viagra.Cialis Professional.Propecia.Soma.Viagra Super Force….

Leave a Reply