Archive for February 18th, 2010


BitmapData.draw & Matrix – how to copy a section out of the middle of an image

Okay, if you google this, you’ll find TONS of people frustrated with the BitmapData class’s draw method. The livedocs are pretty vague here. They don’t really tell you how to use the matrix variable you can pass draw, and they kinda make it sound like the clipRect rectangle would let you arbitrarily cut out any size and shape from the drawable source. That’s almost true. What they don’t tell you is that the section you cut out will remain at the x/y coordinates from which you cut it.

So, let’s say you have a 100×100 image, and you want a copy of the section from 10/20 to 20/30. You might think it would be this easy:

var bmpData:BitmapData = new BitmapData(10,10);// a new 10x10 image
var rect:Rectangle = new Rectangle(10,20,10,10);

Truth is, it’s not much harder, but that bit of code will not give you what you want. The bit you grabbed from 10/20 to 20/30 will remain at those coordinates in your output, and since you only made a 10×10 image, it will be empty.

Here’s the code you want:

var bmpData:BitmapData = new BitmapData(10,10);// a new 10x10 image
var matrix:Matrix = new Matrix();
var rect:Rectangle = new Rectangle(10,20,10,10);

Your clipRect, there, will take the section you want, and the matrix transformation will translate it back to 0/0.