18
Feb
10

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);
bmpData.draw(drawableItem,null,null,null,rect);

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();
matrix.translate(-10,-20);
var rect:Rectangle = new Rectangle(10,20,10,10);
bmpData.draw(drawableItem,matrix,null,null,rect);

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

Advertisements

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


  1. 1 Steve
    August 4, 2011 at 5:09 pm

    Thanks so much. You don’t know how many hours I’ve had my head wrapped around this and still not being able to get it to work was getting frustrating.

  2. February 20, 2014 at 7:13 pm

    Thank you! Amazing Adobe’s documentation doesn’t explain this.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: