Categories
misc

Aligning in Actionscript

Ever had to align something in as3 before?

How many times have you typed something like this to centre align a display object?

child.x = (parent.width - child.width) / 2;

Well no more!

introducing align.as!!!

This is a class I have been using for years and always meant to share but never got round to it.

Here is how it works:

//to centre align a display object with its parent:
align(child);
 
//to top-right align a display object with its parent:
align(child, null, [1, 0]);
 
//to bottom-right align a display object with its parent:
align(child, null, [1, 1]);
 
//to centre align a display object with respect to the stage:
align(child, stage);
 
//to top-centre align a display object with respect to the stage and offset it by 25 pixels in the y direction:
align(child, stage, [0.5,1], [0,25]);

Why it works:

parameter 1 – the display object to align
parameter 2 – the object to align against (if null it will use the child’s parent)
note: this can be a display object or an array of length 2 (element 0 being width and 1 being height) comes in handy if you want to align against some values not relating to a specific display object
parameter 3- the alignment in array form! element 0 is the alignment in x-direction and element 1 is the alignment in the y-direction… [0,0] = top left, [1,1] = bottom right, [0.5,0.5] = middle centre (also the default if you pass in null)
parameter 4 – an optional offset array in pixels i.e. an array here of [50,-100] would offset the display object by +50 in the x direction and -100 in the y direction, after the object has been aligned!

Its not perfect but I use it all the time!!! Brilliant in resize event handlers:
i.e.

align(_contact, stage, [0.5, 1], [0,-25]);
align(_content, stage);
align(_bg, stage, null, [0,-50]);
align(_spinner, _content, null, [_content.x+_spinner.width/2, _content.y+_spinner.height/2]);

just a small snippet from a resize handler in one of my projects… really really speeds things up when it comes to aligning

please use it and please feedback, especially if it breaks/dies/explodes

I plan to add support for detecting bounds as at the moment it is geared at top left aligned display objects only (although you can use the offset to overcome this if you wish)

let me know what you think

b

EDIT: the following link has been updated to include the features as described in the next post, ensure you download the latest version number
the download link —-> bwhiting v1.1 <----