AS3 display object height not reported correctly

156 views Asked by At

This should be simple. What am I missing? Create a Sprite (container), put it on the displaylist, add a new Sprite (rect) to container. Change height of the child (rect). Height values of both parent (container) and child (rect) are not reported correctly although rendered correctly. Thanks for your assistance.

var container:Sprite = new Sprite();
addChild(container);

[Embed(source = "../lib/rectangle.swf")] // height is 100
var Rect:Class;
var rect:Sprite = new Rect();

trace(rect.height); // 100 is correct before placement in container
container.addChild(rect);
trace(rect.height); // 100 is correct after placement in container
trace(container.height); // 0 is not correct; should be 100

rect.height = rect.height + 100; // renders correctly at new height
trace(rect.height); // 100 is not correct; should be 200
trace(container.height); // 0 is not correct; should be 200
1

There are 1 answers

0
Vesper On

Apparently your container is not on the stage display list. If a measured DisplayObject is not on the display list (anywhere), its dimensional properties are not properly recalculated, when its own display list is altered. This is apparently to save time for Flash engine to process building of a complex MovieClip frame or any other complex container faster, and recalculation is only done if the container is placed to stage. The resolution is to place the object to be measured to stage (anywhere, anyhow), gather its properties then remove it from stage. An example:

trace(this.stage); // [object Stage] - to make sure we can access stage in here
var sp:Sprite=new Sprite();
var b:Bitmap=new Bitmap(new BitmapData(100,100)); 
trace(sp.width); // should return 0
trace(sp.height); // 0 also
sp.addChild(b);
trace(sp.height); // 0 again
trace(b.height); // should return 100, as the bitmap data is specified
// as well as in your case, the class's width and height are precalculated
addChild(sp);
trace(sp.height); // returns 100, as expected
removeChild(sp);
trace(sp.height); // 100, stored
sp.removeChild(b);
trace(sp.height); // should also return 100, while there's no content in the sprite

There is also another possibility, width of an object off stage can be in the negative, the solution is again the same - put object on stage, get width, remove object from stage.