I was having a hard time drawing a Flex BitmapData object (or Bitmap) to a canvas. Since neither of these objects are UIComponents, they cannot be added directly as children to a Canvas using the AddChild method-you’ll get a runtime error. After poking around the web, I quickly found a suggestion to simply add the Bitmap to a UIComponent like Sprite or Image and then add that to the Canvas. Like this:

var myBitmap:Bitmap = new Bitmap(myBitmapData);
var myImage:Image = new Image();
myImage.addChild(myBitmap);
myCanvas.addChild(myImage);

So this method will get your Bitmap/BitmapData onto the canvas. But then we have a new problem: if the image is larger than the canvas, the image will extend outside the limits of the canvas, even if the canvas has scrollbars enabled (the large image does not even activate the canvas scrollbars). This was no good for me. I wanted to be able to scroll the canvas to view the entire image.

The solution that worked better than the AddChild method above was to instead set the Image.source property to the Bitmap.  Like this:

var myBitmap:Bitmap = new Bitmap(myBitmapData);
var myImage:Image = new Image();
myImage.source = myBitmap;
myCanvas.addChild(myImage);

Presto! The BitmapData is displayed in the canvas and we get nice scrollbars.

  • Share/Save/Bookmark