`

Saturday, September 18, 2010

Rotating BitmapData with Actionscript 3

Here’s a little snippet – rotating BitmapData (through 90 degrees) with Actionscript 3.

|| -----------------------------------------------------------  ||


var bd:BitmapData;
var bmp:Bitmap;

var matrix:Matrix = new Matrix();

var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
loader.load(new URLRequest("right.png"))


function imageLoaded(event:Event):void{
    bd = new BitmapData(loader.content.width,  loader.content.height, true, 0x000000);
   
    matrix.translate(-bd.width / 2, -bd.height / 2);
    matrix.rotate(180 * (Math.PI / 180));
    matrix.translate(bd.height / 2, bd.width / 2);

    bd.draw(loader, matrix);
    bmp = new Bitmap(bd);
    bmp.x = stage.stageWidth / 2 - bmp.width / 2;
    bmp.y = stage.stageHeight / 2 - bmp.height / 2;
    addChild(bmp)
   
}

||  ---------------------------------------------------------   ||
 
 
The code above can rotate an images BitmapData, using a Matrix to transform the image when you draw the data.  It’s only really designed to rotate the image in 90 degree increments though – so be aware of that.
How it actually works is to create a new Matrix object, offset the source BitmapData’s width and height (so the rotation goes from the center of the bitmap), rotate the BitmapData, move the BitmapData again (to undo the previous offset), create a new BitmapData object to draw the rotated BitmapData into, and finally draw the source BitmapData with our newly created Matrix.
 


Preview 

Download .zip

No comments: