8bitrocket Diatribe: Drawing Vector Primitives into a BitmapData Object in AS2 and AS3.
That doesn’t sound too difficult, and it really isn’t. I received an email question this weekend from a game developer who was stumped at how to accomplish this in AS2. I knew it was pretty easy to do in AS3 (I think Moock has an example in his latest book), but I had never tried it in AS2. Anyway, it turned out to be pretty easy, with one minor exception that I have yet had time to figure out. The below examples basically draw a vector primitive square on the screen and then take a BitmapData snapshot and re-draw that snapshot to the screen from the BitmapData. The square is a simple 20×20 at 0x,0y and then takes the snapshot and paints the BitmapData version at 0x, 50y. When I made a BitmapData object the exact size, 20 x 20, the right side and bottom are clipped in the copy. So, I just made the BitmapData object 21×21 and it looks fine. I hate crap like that though, but don’t have time tonight to get it to work without the 1 pixel size extension on each axis.
Anyway, since I don’t have to to make this into a full tutorial, here is the code and the example of the AS2 version: I just dropped the code on the main timeline.
AS2 Version:
[cc lang=”javascript” width=”550″] //AS2 import flash.display.BitmapData; import flash.geom.*; this.createEmptyMovieClip(“drawCanvas”,this.getNextHighestDepth()); var tempBitmap:BitmapData = new BitmapData(21,21); this.createEmptyMovieClip(“bitmapHolder”,this.getNextHighestDepth()); |
Nothing tricky going on here. Just create a MovieClip to use as a drawing canvas for the vector shape. Draw on it in and draw() that into a BitmapData object.
Here is the working example:
/downloads/blog/draw_intobitmapdata/as2_squaretobmd.swf
Here is the AS3 version:
[cc lang=”javascript” width=”550″] //AS3 import flash.display.*; import flash.geom.*; var drawCanvas:Shape=new Shape(); var tempBitmap:BitmapData = new BitmapData(21,21); |
This is even easier than the AS2 version because AS3 contains an actual Shape() class to use instead of a MovieClip for a canvas. Just draw into a Shape instance and the draw() in into a BitmapData object.
Here is the working example: