Evenly Aligning an Array of DisplayObjects.

When working with dynamic content, it is often necessary to arrange items evenly within a particular area. The following function takes an array of DisplayObjects and also the desired width they should occupy, and then spaces them out so they fit within it. I have added an optional parameter so that you can set wether the object is centered at the top left, if it is false then it assumes it is centered from the center.

private function spaceHorizontally( width:int, objects:Array, regIsTopLeft:Boolean = false ):void
		{
			//this variable defines the spacing between each item. we do it by dividing the amount of total items we are going to place by the desired size.
			var xSpacing:int = ( width / objects.length );
			var ctr:int;
			var displayObject:DisplayObject;
			
			for( ctr = 0; ctr < objects.length; ctr++)
			{
				displayObject = objects[ ctr ];
				//place the objects at the xSpacing * the current object. Then center within this area.
				displayObject.x = ((xSpacing * (ctr+1)) - xSpacing/2) 
					
					
				//this will correct the top left positioning offset 
				if( regIsTopLeft )
				{
					displayObject.x -= (displayObject.width/2);
				}	
			}
		}

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInShare on RedditShare on StumbleUponShare on TumblrEmail this to someone

Leave a Reply

Your email address will not be published.