Avg. Rating 4.5

Problem

You want to take a snapshot of a Flex container or control at runtime and save it as a BitmapData object.

Solution

The following example shows how you can take a snapshot of an item on the display list using the static ImageSnapshot.captureBitmapData() method, which returns a BitmapData object, as seen in the following snippet: var imageBitmapData:BitmapData = ImageSnapshot.captureBitmapData(source); swfLoader.source = new Bitmap(imageBitmapData);

Detailed explanation

In the following example, clicking the "Take snapshot of DataGrid" button uses the static ImageSnapshot.captureBitmapData() method to return a BitmapData object which in turn is converted into a Bitmap object that is loaded into a SWFLoader control:

<mx:Script>
<![CDATA[
import mx.graphics.ImageSnapshot;

private function takeSnapshot(source:IBitmapDrawable):void {
var imageBitmapData:BitmapData = ImageSnapshot.captureBitmapData(source);
swfLoader.source = new Bitmap(imageBitmapData);
}
]]>
</mx:Script>

<mx:Array id="arr">
<mx:Object col1="Row 1, Col 1" col2="Row 1, Col 2" />
<mx:Object col1="Row 2, Col 1" col2="Row 2, Col 2" />
<mx:Object col1="Row 3, Col 1" col2="Row 3, Col 2" />
<mx:Object col1="Row 4, Col 1" col2="Row 4, Col 2" />
<mx:Object col1="Row 5, Col 1" col2="Row 5, Col 2" />
<mx:Object col1="Row 6, Col 1" col2="Row 6, Col 2" />
</mx:Array>

<mx:ApplicationControlBar dock="true">
<mx:Button label="Take snapshot of DataGrid"
click="takeSnapshot(dataGrid);" />
</mx:ApplicationControlBar>

<mx:HBox>
<mx:DataGrid id="dataGrid" dataProvider="{arr}" />
<mx:SWFLoader id="swfLoader">
<mx:filters>
<mx:DropShadowFilter />
</mx:filters>
</mx:SWFLoader>
</mx:HBox>

NOTE: The ability to load a ByteArray object directly into a SWFLoader control was added in Flex 3 build 187814.

For more information, see http://blog.flexexamples.com/2007/11/17/taking-screenshots-in-flex-3-using-the-imagesnapshotcapturebitmapdata-method/  and http://blog.flexexamples.com/tag/imagesnapshot/.

Report abuse

Related recipes