AS3 Quick Grid Layout – Fluid Row Height
Tuesday, August 25th, 2009I write this kind of quick grid layout all of the time to arrange items within my Flash apps. I thought I’d share my method for those of you who might be looking for a simple method for laying out n number of items.
This variation takes in to account varying heights for the items in each row. You can configure the number of columns to display as well. This code can easily be modified to change these parameters or to set number of rows as the primary setting instead of columns. You will notice in this example I use little boxes, you would swap out the “item” (sprite, movie clip, etc.) that you would want in the grid in place of this. Hope this proves useful for some of you.
/************************************/
//Pixelfumes 2009 - Ben Pritchard
//AS3 Quick Grid Layout - Fluid Row Height
/************************************/
//items in the grid
var nItems:uint = 10;
//number of columns desired
var nCols:uint = 4;
//col and row padding
var padding:uint = 3;
//loop vars
var nCreated:uint = 0;
var tallestItem:Number = 0;
var lastItem:Object;
for(var i:uint=0;i<nItems;i++){
//swap this block for whatever item is
//being used in the grid
var item:Sprite = new Sprite();
item.graphics.beginFill(0xCCCCCC);
item.graphics.drawRect(0,0,30,30);
item.graphics.endFill();
//add the item to the grid
addChild(item);
//keep track of the tallest item in this row
if(item.height > tallestItem){
tallestItem = item.height;
}
//if we are not on the very first item
if(nCreated != 0){
//have we reached the max col for this row
if(nCreated % nCols == 0){
item.x = 0;
item.y = lastItem.y + tallestItem + padding;
tallestItem = 0;
}else{
item.x = lastItem.x + lastItem.width + padding;
item.y = lastItem.y;
}
}
nCreated++;
//update last item
lastItem = item;
}