Recipe 8.3. Drawing a Display Object to a Bitmap


Problem

You have some graphical content in a sprite or other display object and want to draw that to a bitmap.

Solution

Use the BitmapData class's draw( ) method to draw the content onto the bitmap.

Discussion

When you first create a BitmapData, it is simply a blank rectangle of whatever color you specified. You may have some existing graphic content in a movie clip, sprite, or other display object that you would like to draw to the new bitmap. The draw( ) method allows you to do just this. You pass the object you want to draw into the draw( ) method of the BitmapData you want to draw it onto. You can also pass an instance of the flash.geom.Matrix class to the method. The Matrix class allows you to scale, rotate, translate, or skew the object's graphics before they are drawn. This parameter is optional, but if you need to use later parameters and don't want to transform the object, just pass null. You can also optionally pass a ColorTransform object, which alters the color of the object before it is drawn. See Recipe 10.1 for information on ColorTransforms. The following example draws a sprite, named _sprite, into a BitmapData named bitmap, with no transformation:

bitmap.draw(_sprite);

One reason why this becomes important is because the BitmapData class has few tools for basic drawing. You can set a pixel to a particular color, create a filled rectangle, or do a flood fill. There are some specialized noise functions, but it lacks basic functions such as line, curve, oval, or outline drawing tools. To overcome this, you can use the drawing API methods to draw content into a movie clip or sprite, and then draw that object into the bitmap. The following example creates a BitmapData and a Sprite. It then uses the drawing API to draw an oval in the sprite and draws the sprite into the BitmapData:

var bitmap:BitmapData = new BitmapData(100, 100,                                      true, 0x00ffffff); var sprite:Sprite = new Sprite(  ); sprite.graphics.beginFill(0xff0000, 100); sprite.graphics.drawEllipse(0, 25, 100, 50); sprite.graphics.endFill(  ); bitmap.draw(sprite);

Notice that the bitmap's background has been made transparent (0xffffff), so although the bitmap itself is actually a rectangle, all you see is the oval that has been drawn to it.

See Also

Recipe 8.1 for how to create a bitmap, Recipe 8.2 for information on how to make a BitmapData visible, and Recipe 10.1.




ActionScript 3. 0 Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2007
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net