Scaling a container does not affect width of child
I've got a container(sprite) with children(sprites) added to it. When I scale the container, I would like to get the new width of a child, but when I trace the children's width I always get the original dimensions, even though everything gets visually scaled as it should. How do I overwrite the children-width ?
Update: I just found out that the children.graphics-"dimensions" could have caused the problem. When I leave the graphics, everything seems ok. Is it possible to scale the graphics at same time as the child-s开发者_JAVA百科prite?
You can use DisplayObject.transform.pixelBounds.width
or DisplayObject.transform.pixelBounds.height
to get the width and height of the child display objects like in the following:
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}// end function
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
var squaresXml:XML =
<squares>
<square name="redSquare" color="0xFF0000" />
<square name="blueSquare" color="0x00FF00" />
<square name="greenSquare" color="0x0000FF" />
</squares>;
var size:Number = 100;
var squares:Sprite = new Sprite();
for (var i:uint = 0; i < squaresXml.children().length(); i++)
{
var square:Square = new Square(squaresXml.square[i].@color, size);
square.name = squaresXml.square[i].@name;
square.x = i * size;
squares.addChild(square);
}// end for
addChild(squares);
squares.scaleX = squares.scaleY = 2;
var redSquare:Square = squares.getChildByName("redSquare") as Square;
trace(redSquare.width); // output: 100
trace(redSquare.transform.pixelBounds.width); // output : 200;
}// end function
}// end class
}// end package
import flash.display.Shape;
import flash.display.Sprite;
internal class Square extends Shape
{
public function Square(color:uint, size:Number)
{
graphics.beginFill(color);
graphics.drawRect(0, 0, size, size);
graphics.endFill();
}// end function
}// end class
DisplayObject.transform.pixelBounds
basically gets "a Rectangle
object that defines the bounding rectangle of the display object on the stage".
The children width is always going to be what the original, full scale values are. If you want to get their current width just multiply the value with the scaling ratio of the container.
So for example if your child width is 100 pixels and you scale the container to half size: 100 pixels * 0.5 = 50 pixels. Or with code: actualChildWidth = container.scaleX * child.width;
I would also recommend using the concatenatedMatrix
of your display object's transform. That will return a 2D transformation matrix multiplied up the object's parent chain to the root level.
Once you have the resulting Matrix object, you can inspect its a
or d
property to see its root-level x and y scaling factors respectively.
精彩评论