Tiler Class

October 25th, 2007 by Slav

In html is not unusual to have repeating smaller images or “tiles” filling up your background. In fact this blog has one as well.

In flash however, you don’t see this functionality very often. There are several reasons for that :

To determine how many tiles you need to fill up the space , you need to know it’s dimensions. You can only know that once the tile is fully loaded.  Which is fine, you can load one tile, get it’s width and height, then determine how many you need to place vertically and horizontally and at what exact positions. And then all you need to do is to use duplicateMovieClip method to duplicate all the tiles off the first one you loaded. Right ?

Wrong. Due to the security restrictions you can’t duplicate the movieclips containing the assets that have been loaded externally. Fortunately came flash 8 and BitmapData. So you can use draw command to render the rest of the tiles on the stage.

here is the code that does just that :

for (var i : Number = 0; i < totalTiles; i++)
  {
   var matrix:Matrix = new Matrix();
   matrix.translate(tileGrid.getXpos(tilesAttached),tileGrid.getYpos(tilesAttached));
   visuals.draw(firstTile,matrix);
   tilesAttached++;    
  }

For those users with old flash plugin, it will still work as Tiler class detects whether the user has plugin version > 8, and if so it uses more efficient BitmapData.draw approach, but if not, it will still load each tile separately.

This class has a method call rebuild(), which is useful when user re-sizes the stage, and you have suddenly more space to fill.

To use this class you just need 2 simple lines of code :

1. create new instance of Tiler, tell him on which timeline to render the tiles, what graphic to use, and whether to load graphics from external file or attach from the library

tiler = new Tiler(tiles_mc,"images/bg_tile.jpg",false);

2. tell it to create tiles, with optional x and y offset, and whether to repeat the tiles on x and y axis.

tiler.createTiles(0,0,true,true);

I included the 2 simple demos that demonstrate using this class both with external images, and library assets.

Flash CS3 Version

Flash 8 Version

Posted in AS2, flash

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.