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.
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!