Friday 10 February 2012

Why BitmapData?

One topic I've seen discussed a few times online is what the best format for graphics in Flash is. And the answer is almost always the Bitmap and BitmapData classes. The overriding reason for this is performance, but it is worth looking at the alternatives to consider why this might be.


The BitmapData class stores raw graphics data. As such it has a number of methods but only a few properties, for its dimensions and whether it supports transparency. To add it to the stage another class is needed, the simplest of which is the Bitmap class. The Bitmap class minimally extends the DisplayObject class, the base class for all drawable objects (as only DisplayObjects can be added as children to containers).


The Bitmap contains all the properties needed to display a Bitmap. Using the Bitmap's fields (all inherited from DisplayObject) a BitmapData can be positioned, rotated, scaled, arbitrarily transformed (with the 3 × 3 Matrix), recoloured, or have a filter added.


And these operations need not be too expensive because of another Bitmap property, cacheAsBitmap. This tells the graphics system to not recalculate the how to draw the Bitmap if it doesn't change (it can move by changing its x and y but not much else). cacheAsBitmap is enabled by default if filters are used but has to be enabled manually otherwise.


The separation of the Bitmap and BitmapData classes means that a BitmapData need only be loaded once. It can then be drawn multiple times, using multiple Bitmaps. The BitmapData can be changed and this change will be reflected across all Bitmaps.


There are other classe that can be used to put graphics onscreen, but they are much more expensive. The main ones are the SimpleButton and MovieClip, both of which extend the InteractiveObject class. This means they respond to, and so check for, events which are slow in Flash. MovieClip also extends DisplayObjectContainer which means it can contain children, making extra work for the garbage collector.


In some ways it's odd there is nothing between Bitmap and these other classes, such as a class for animations that doesn't also handle events and act as a container. So even for animations it can make sense to turn them into BitmapData, advancing their frames by updating the bitmapData field of the containing Bitmap, to avoid the overhead of the MovieClip class.

No comments:

Post a Comment