Recently I had most rewarding moments while playing around with Bitmap and BitmapData classes in ActionScript3.0 and also I must mention how this becomes more fun than really learning the language.

While reading about copying pixels from one Bitmap to another this idea fall into my mind about writing function to allow me to split any loaded or drawn image into desired number of columns and rows. Solution was quite easy actually, with a little help of ByteArray class.

Here is the function which allows you to do just that, dynamic split of any image:


function splitBitmap(_source:BitmapData, _columns:int, _rows:int):void
{
var _bitmapWidth:int = _source.width;
var _bitmapHeight:int = _source.height;

var _onePieceWidth:Number = Math.round(_bitmapWidth / _columns);
var _onePieceHeight:Number = Math.round(_bitmapWidth / _rows);

var _copyRect:Rectangle = new Rectangle(0, 0, _onePieceWidth, _onePieceHeight);
for(var i:int = 0; i < _columns; i++)
{
var tempArray:Array = new Array();

for(var j:int = 0; j < _rows; j++)
{
var _piece:String = "piece"+String(i)+String(j);
var temp:* = [_piece];
temp = new BitmapData(_onePieceWidth, _onePieceHeight, true, 0xFF0000CC);

var newBytes:ByteArray = _source.getPixels(_copyRect);
newBytes.position = 0;
temp.setPixels(_copyRect, newBytes);

var _newBitmap:String = "newBitmap"+String(i)+String(j);
var tempBitmap:* = [_newBitmap];
tempBitmap = new Bitmap(temp);

tempBitmap.x = i * (_onePieceWidth) + bm1.x;
tempBitmap.y = j * (_onePieceHeight)+ bm1.y;
addChild(tempBitmap);

tempArray.push(tempBitmap);
}
bitmapsArray.push(tempArray);
}
}


Setting tempBitmap x and y properties is optional, because I wanted to put new pieces in original place (above bm1, original Bitmap) so viewer can't see these are new

DisplayObjects. In this way transition effect is masked. You may also notice bitmapsArray, two-dimensional Array to hold all pieces in one place for later easy manipulation.

There can be some improvements to it, like limiting max number of columns and rows or adding image import with Loader class etc. but main functionality is there, working like a charm. Now, you can use this function to produce all kinds of transition effects and image manipulations. Some examples might follow in future posts.

*_*