views:

1121

answers:

2

I'm currently working on a flash game and I need to know how to addChild a BitmapData or draw a BitmapData to screen. If I can't than how can I give a DisplayObject my BitmapData?

+1  A: 

Here's an example of an AIR app thrown together to illustrate one way to do it, assuming I've understood the question correctly:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="onCreationComplete()">

    <mx:Script>
     <![CDATA[

      import mx.core.UIComponent;

      private function onCreationComplete():void
      {
       // Some sample bitmap data
       var bmpd:BitmapData = new BitmapData(50, 50, false, 0xFF0000);

       // Create a new bitmap, created from the data
       var bmp:Bitmap = new Bitmap(bmpd);

       // Wrap the bitmap in UIComponent
       var uic:UIComponent = new UIComponent();
       uic.addChild(bmp);

       // Add your UIComponent to the display list
       addChild(uic);
      }

     ]]>
    </mx:Script>

</mx:WindowedApplication>

Essentially what you need to know is that your BitmapData first needs to be wrapped in a Bitmap object, and that the resulting Bitmap object is a DisplayObject, so before it can be added to the display list, it needs to be wrapped in a UIComponent instance.

That's one way, but again, it largely depends on what you're trying to do specifically, so if this doesn't quite apply in your case, feel free to post back and I'll adjust accordingly. Hope it helps!

Christian Nunciato
+3  A: 

BitmapData objects cannot be added directly to the screen since they aren't descendants of DisplayObject. If you'd like to display the contents of a BitmapData object, you'll need to use a Bitmap, and it's bitmapData property. If you're using Flex, you'll need to make sure that you're placing the Bitmap into an instance of UIComponent or one of it's subclasses. Otherwise, if you're just using AS3 in Flash, this will do it:

    package
{
 import flash.display.Bitmap;
 import flash.display.BitmapData;
 import flash.display.Sprite;
 import flash.geom.Point;

 public class BitmapDataExample extends Sprite
 {
  public function BitmapDataExample()
  {
   super();

   var canvasSize:uint = 100;
   var size:uint = 5;
   var bd:BitmapData = new BitmapData (canvasSize, canvasSize, false, 0x000000);

   var bmp:Bitmap = new Bitmap (bd);
   addChild(bmp);

   // everything from this point on is just drawing junk into the BitmapData object
   var p:Point = new Point (0, 0);
   for (var y = 0; y < canvasSize; y++)
   {
    p.y = y;

    for (var x = 0; x < canvasSize; x++)
    {
     p.x = x;

     if (p.x % size == p.y % size)
      bd.setPixel(p.x, p.y, 0x00FF00);
    }
   }
  }

 }
}
joshbuhler