How do I calculate the size of the sprite?

I have a sprite in which I am doing some custom drawing, but I would like the container to know where to position the sprite correctly. To do this, the container needs to know how big the sprite is. UIComponents go through the measurement stage, but sprites don't. How do I calculate the size of the sprite?

Edit: I am doing the drawing in Event.ENTER_FRAME and it is animated, so I cannot tell in advance how big it will be. The UIComponent has a measurement function and I would like to create something similar.

0


source to share


5 answers


The exact answer, as far as I can tell, you cannot tell in advance, you have to draw the sprite to determine its size.



+2


source


The sprites take the size you draw in them. It doesn't have any size until you draw something in it. If your application allows you to draw a border (rectangle) first and then measure the sprite. But don't go beyond the boundaries later.



+1


source


Also, depending on what you are drawing, you can use math to pre-calculate the final size.

i.e. if you are drawing a circle you can use Math to determine the final height / width.

microphone

+1


source


Take a look here - hopefully 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 a sprite simply by querying its height and width properties.

0


source


If you need to unfold some other components based on the Sprite's width and height, but before drawing it, you can draw a flash.display.Shape object, use that dimension as a reference, and then attach the Shape on the Sprite.

0


source







All Articles