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.
source to share
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.
source to share