6/20/2011

BitmapFill and Tiles (and scrolling it infinitely)

You might know about the beginBitmapFill method of the Graphics class. It is perfect for creating tiles that repeat itself. And with matrixes, we can even make it scroll infinitely.

The Method
Adobe Documentation
beginBitmapFill behaves much like beginFill but instead of a color, it uses BitmapData instead. If you bothered to look at that documentation link, you'll notice that the third parameter of the method determines if the bitmap image repeats itself or not. It is true by default. This is useful in creating a tile background (like in a game). It is pretty simple and can be done like so: import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Sprite; var pic:Bitmap; // a Bitmap (reference or instantiate yourself) var bmd:BitmapData=pic.bitmapData; //get BitmapData from Bitmap var bg:Sprite=new Sprite(); bg.graphics.clear(); bg.graphics.beginBitmapFill(bmd); bg.graphics.drawRect(0,0,stage.stageWidth,stage.stageHeight); addChild(bg); Here's the above code in effect... tiling...


Applying Matrix Transformations to it
Notice that the beginBitmapFill method takes a Matrix for its second parameter. This performs a matrix transformation on the bitmap data. Learning matrix transformations means a whole 'nother post or two. There are plenty of tutorials on it out there. Some simple supplied methods of the Matrix class are translate, scale and rotate. Here's a sample code doing a simple x translate. (notice the tiling still in effect) import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Sprite; import flash.events.Event; var pic:Bitmap; // a Bitmap (reference or instantiate yourself) var bmd:BitmapData=pic.bitmapData; //get BitmapData from Bitmap var mat:Matrix=new Matrix(); // Matrix for our transformation var bg:Sprite=new Sprite(); addChild(bg); bg.addEventListener(Event.ENTER_FRAME,draw); function draw(e:Event):void{ mat.translate(5,0); // translate 5 pix right on x coordinate bg.graphics.clear(); bg.graphics.beginBitmapFill(bmd,mat); bg.graphics.drawRect(0,0,stage.stageWidth,stage.stageHeight); }

adding some interactivity...
source (uses Greensock's ImageLoader - part of the LoaderMax package)

Naturally, one would consider using this for a easy ready-made looping gallery. But before you do that, consider how everything needs to be converted to bitmap data. The larger the images are, the more taxing it is to draw that bitmap data. Also, adding interactivity would require a little more implementation, as all the images would behave as one bitmap. It is certainly viable, but be sure to test it first. This method is best used for tiling images that need no interactivity.

3 comments:

  1. Thanks man, I liked this post. Helped me a lot ;)

    ReplyDelete
  2. sorry guys, my file host is down... gimme a bit to get them back

    ReplyDelete