Tuesday, 13 December 2011


The Matrix class in Flash is a two-dimensional matrix, used to draw and display objects on the stage. It is difficult to avoid as it is needed for some calls, especially the draw function of the BitmapData class. The Matrix if something is to be drawn without moving, but generally it's required.

The simplest use is to offset something as it is drawn. I find this is also the most common use, so it's useful to have a quick way to do it. Here's an example of that, drawing a wall block into a layer based on its grid position.

function DrawWall(iX:int, iY:int):void {
 var fX:Number = Game.kiTowerSize * iX;
 var fY:Number = Game.kiTowerSize * iY;
 baseBmp.draw(dataWall, new Matrix(1, 0, 0, 1, fX, fY));

The last line creates a Matrix to offset the object being drawn by fX and fY, the Matrix created inline for passing to draw. The '1, 0, 0, 1' specifies that it is not rotated or scaled (they are the four elements of a 2x2 identity matrix). It is done over three lines as the last line would otherwise be too long.

The following in contrast scales without any offset, to shrink a larger BitmapData into a smaller one

fScale = bitmapData.width / tmpBase.width;
bitmapData.draw(tmpBase, new Matrix(fScale, 0, 0, fScale, 0, 0),
 null, null, null, true);

No comments:

Post a Comment