Code Snippet: Generate Checkerboard Pattern

checkerboard

Pure solid backgrounds are getting just a little too plain for me of late. The alternative is to provide a pattern. Now you can use an image- where the size of the background determines the file size (not cool) or you could just procedurally generate one (file size determined by code size).

Here is a snippet of code to generate a checkerboard pattern, as seen to the left. The code works by simply providing the size of the area to fill. There are further optional parameters to control the cell size (32×32) and colors (0xffe7e6e6, 0xffd9d5d5).

On a side note, I found this awesome cake whilst googling the correct use of the word checkerboard.

package net.avdw.generate
{
	import flash.display.BitmapData;
	import flash.geom.Rectangle;

	public function generateCheckerboard(width:int, height:int, cellWidth:int = 32, cellHeight:int = 32, color1:uint = 0xffe7e6e6, color2:uint = 0xffd9d5d5):BitmapData
	{
		var bitmapData:BitmapData = new BitmapData(width, height);
		var numRows:int = Math.ceil(height / cellHeight);
		var numCols:int = Math.ceil(width / cellWidth);

		var clipRect:Rectangle = new Rectangle(0, 0, cellWidth, cellHeight);

		var y:int;
		var x:int;
		var lastColor:uint = color1;

		for (y = 0; y < numRows; y++)
		{
			for (x = 0; x < numCols; x++)
			{
				clipRect.y = y * cellHeight;
				clipRect.x = x * cellWidth;
				bitmapData.fillRect(clipRect, lastColor);

				lastColor = (lastColor == color1) ? color2 : color1;
				if (x + 1 == numCols && x % 2 != 0)
					lastColor = (lastColor == color1) ? color2 : color1;
			}
		}

		return bitmapData;
	}

}