views:

846

answers:

5

I have a sprite that I do some custom drawing in, but I would like the container to know where to position the sprite properly. To do this, the container needs to know how big the sprite is. UIComponents go through a measure stage, but sprites don't . How do I calculate the size that a sprite will be?

Edit: I'm doing the drawing in Event.ENTER_FRAME, and it's animated, so I can't tell ahead of time how big it's going to be. The UIComponent has a measure function and I'd like to create something similar.

A: 

Sprites take the size that you draw in them. It has no size at all until you've drawn something in it. If your application allows you can draw a border (rectangle maybe) first and then measure the sprite. But don't draw outside the borders later.

PEZ
A: 

Have a look here -- I hope this answers your question:

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

    <mx:Script>
     <![CDATA[

      import mx.core.UIComponent;

      private var s:Sprite;
      private var w:UIComponent;

      override protected function createChildren():void
      {   
       super.createChildren();

       if (!s)
        s = getSprite();

       w = new UIComponent();

       trace("The sprite measures " + s.width + " by " + s.height + ".");

       w.addChild(s);
       box.addChild(w);
      }

      private function getSprite():Sprite
      {
       var s:Sprite = new Sprite();
       s.graphics.lineStyle(1, 0xFFFFFF);
       s.graphics.beginFill(0xFFFFFF, 1);
       s.graphics.drawRect(0, 0, Math.floor(Math.random() * 1000), Math.floor(Math.random() * 1000));
       s.graphics.endFill();

       return s;
      }

     ]]>
    </mx:Script>

    <mx:Box id="box" backgroundColor="#FFFFFF" />

</mx:Application>

If you run this, the trace statement should display the height and width of the drawn Sprite, which is randomly generated. In other words, you can get the height and width of the sprite simply by querying its height and width properties.

Christian Nunciato
Just keep in mind that width does not take into account where in the DisplayObject the graphics are, so, if you're drawing in negative x or y you will need to use getBounds() to make sure you can position it correctly.
grapefrukt
+1  A: 

The precise answer, as far as I can gather is, you can't tell ahead of time, you must actually draw into the sprite to determine it's size.

Mark Ingram
A: 

If you need to layout some others components based on the Sprite width and height, but before actually drawing it, you can draw on a flash.display.Shape object, use this size as a reference, and then attach the Shape on the Sprite.

kajyr
+1  A: 

Also, depending on what you are drawing, then you may be able to use math to pre-calculate the final size.

i.e. if you are drawing a circle, you could use Math to figure out the final height / width.

mike

mikechambers