AS3: Grid

View Example
View Documentation
Download Class & Example Files

UPDATE 9/26/08: I have updated the code to reflect the changes outlined in the comments below by Skye Giordano. Thanks Skye!

The Grid class is a layout utility that returns an array for laying out objects in a grid.

Actionscript:
  1. package com.reintroducing.layout
  2. {
  3.     import flash.geom.Point;
  4.    
  5.     /**
  6.      * A layout utility that returns an array for laying out objects in a grid.
  7.      *
  8.      * @author Matt Przybylski [http://www.reintroducing.com]
  9.      * @version 1.1
  10.      */
  11.     public class Grid
  12.     {
  13. //- PRIVATE & PROTECTED VARIABLES -------------------------------------------------------------------------
  14.  
  15.        
  16.        
  17. //- PUBLIC & INTERNAL VARIABLES ---------------------------------------------------------------------------
  18.        
  19.         public static const DEFAULT_NAME:String = "com.reintroducing.layout.Grid";
  20.        
  21. //- CONSTRUCTOR -------------------------------------------------------------------------------------------
  22.    
  23.         public function Grid():void
  24.         {
  25.            
  26.         }
  27.        
  28. //- PRIVATE & PROTECTED METHODS ---------------------------------------------------------------------------
  29.        
  30.        
  31.        
  32. //- PUBLIC & INTERNAL METHODS -----------------------------------------------------------------------------
  33.    
  34.         /**
  35.          * Creates the grid and returns an array of points with x and y values based on passed parameters.
  36.          * The $leftToRight addition was contributed by Skye Giordano.
  37.          *
  38.          * @param $columns An integer representing the number of columns to be created in the grid
  39.          * @param $rows An integer representing the number of rows to be created in the grid
  40.          * @param $xSpacing An integer representing the spacing between columns
  41.          * @param $ySpacing An integer representing the spacing between rows
  42.          * @param $xPadding An integer representing the padding between each column
  43.          * @param $yPadding An integer representing the padding between each row
  44.          * @param $leftToRight An optional boolean that creates the grid from left-to-right or top-to-bottom (default: true)
  45.          *
  46.          * @return Array
  47.          */
  48.        
  49.         public static function create($columns:int, $rows:int, $xSpacing:int, $ySpacing:int, $xPadding:int, $yPadding:int, $leftToRight:Boolean = true):Array
  50.         {
  51.             var arr:Array = new Array();
  52.             var pt:Point;
  53.             var row:Number;
  54.             var col:Number;
  55.             var num:int = ($columns * $rows);
  56.            
  57.             for (var i:int = 0; i <num; i++)
  58.             {
  59.                 pt = new Point();
  60.                
  61.                 if ($leftToRight)
  62.                 {
  63.                     row = (i % $columns);
  64.                     col = Math.floor(i / $columns);
  65.                
  66.                     pt.x = (row * ($xSpacing + $xPadding));
  67.                     pt.y = (col * ($ySpacing + $yPadding));
  68.                 }
  69.                 else
  70.                 {
  71.                     row = (i % $rows);
  72.                     col = Math.floor(i / $rows);
  73.                
  74.                     pt.x = (col * ($xSpacing + $xPadding));
  75.                     pt.y = (row * ($ySpacing + $yPadding));
  76.                 }
  77.                
  78.                 arr.push(pt);
  79.             }
  80.            
  81.             return arr;
  82.         }
  83.    
  84. //- EVENT HANDLERS ----------------------------------------------------------------------------------------
  85.    
  86.        
  87.    
  88. //- GETTERS & SETTERS -------------------------------------------------------------------------------------
  89.    
  90.        
  91.    
  92. //- HELPERS -----------------------------------------------------------------------------------------------
  93.    
  94.         public function toString():String
  95.         {
  96.             return "com.reintroducing.layout.Grid";
  97.         }
  98.    
  99. //- END CLASS ---------------------------------------------------------------------------------------------
  100.     }
  101. }

If you found this post useful, please consider leaving a comment, subscribing to the feed, or making a small donation.

18 Comments

This is a very handy class, great job. The create method created points where successive items were ordered left-to-right, then down. That is, it specified a point by row and columns were implied by row ends.

Using some math my brilliant friend, Abram Siemsen at ThoughtProcessInteractive introduced me to several years ago, I modified the class to take an additional argument which specifies whether the array Points should be organized left-to-right (as your original class did), OR top-down (columns first). Abe's method uses the modulus instead of a nested loop.

I've posted the source with example here:
http://drinkspiller.cannonballinteractive.com/code/as3/Grid_LeftToRightOrTopToBottom.zip

In the FLA, change the last parameter in the create method between true and false to order the grid in the opposite direction.

Cheers,

Skye

If you downloaded the file in the last 20 minutes, please download anew, there was a bug in the code, now corrected.

I posted another .zip this morning which includes a fix at the above URL.

Skye,
I've yet to take a look at it as I'm trying to finish up a project currently. When I get some free time I'll make sure to look. Thanks.

[...] wanted to say I updated the AS3 Grid class to reflect the ability to draw the grid from left to right or top to bottom based on the comments [...]

Skye,
I've updated the files with your addition. Thanks for the wonderful input!

thanks for this great class. i have a question: currently you can draw the grid left to right or top to bottom, what would be the easiest way to draw it from center and then clockwise?

thanks for suggestions and help

lauritz,
Unfortunately this class was not built to do such a thing but if there is anyone that wants to take a shot at building it to do so, by all means I'd love to see someone tackle it. My math is very rusty and I just don't think I'd be able to come up with a viable solution without really taking a lot of time to do so, unfortunately.

Nice, thanks.

Out of curiosity how did you get the timeline to not show up when the file is opened. I like that trick.

Kris,
I'm not sure what you mean by timeline not showing up, i assume its because the file is saved in my workspace where on my machine the timeline shows up on my second (right side) monitor. if you want to hide your timeline, you can collapse it or set up your workspace to not show the timeline in the window menu.

This is great. If I wanted to make each grid space a button, is there a way to create on event listener that listens to all of them individually?

Nick,

As you loop through the array and place the items at their grid location, set up your event listener:

for(var i:int =0; i < grid_items.length, i++){
//place item with grid class here, then...
grid_items[i].addEventListener(MouseEvent.CLICK, myHandler, false, 0, true);
}

good job my friend
Im working on some sort of grid manager myself, see if you find usefull..

sorry forgot to post the adress blog.diogolean.com

Hey there,

First of all great little class!! Second, I'm using it to display images in two rows, is there a way to offset the second row so it looks a bit more organic?

Thanks

Jorge

@jorge sanchez: you'll probably want to rip out the code of the method and rewrite it a bit to add offsets to rows. then just count the row (if row == even number) apply offset. hope that helps.

Awesome, thank you. It worked on the first try. Npw I have seen this effect but with multiple loops. I assume this one is quicker and I correct on that?

@Dowdle Puzzles: I'm not sure to be honest. I never ran speed comparisons versus double loops. This uses modulo which isn't the fastest operator in Flash but as long as you're not doing millions of calculations you should have no issues really.

Leave a comment

(required)

(required)