About the Height and Width property of DisplayObject

关于DisplayObject的width和height属性的问题,主要两点记住:

1.当没有使用graphics去绘制内容时, 其width和height一定是0.

2.child DisplayObject对其宽度和高度没有影响。

注意:这里是DisplayObject类和其一些子类。UIComponent并不如此。

There are something to explain about the height and width of DisplayObject.

1: If there is no content in the instance of DisplayObject(except for TextField), then the height of it will be 0 even you set it to some non-zero number”:

       private function testHeight1():void

       {

           var shape:Shape = new Shape();

           shape.height = 10;

           trace(shape.height);

       }

Result:0 

From the code above, we see that the content is null, so we can see that when we get the height from this property:height, we get 0. But we should understand what is content?  Some code showing below:

       private function testHeight2():void

       {

           var shape:Shape = new Shape();

           // draw a rectangle, topleft corner is (0,0),width and height is 100

           shape.graphics.drawRect(0,0,100,100);

           shape.graphics.drawCircle(100,100, 50);

           shape.graphics.drawCircle(0,0,50);

           trace("with content DisplayObject height:"+shape.height);

           trace("with content DisplayObject width:" +shape.width);

}

Result: with content DisplayObject height:200

with content DisplayObject width:200

We see that after we use the graphics of the DisplayObject instance to draw something, the width and height of them is calculated by what the graphics has drawn. What about the child? What is the impact after we add child to the DisplayObject?

2. About the CONTENT of the DisplayObject

       private function testHeight3():void

       {

           var childShape:Shape = new Shape();

           childShape.graphics.drawCircle(0,0,200);

           var sprite:Sprite = new Sprite();

           sprite.height = 20;

           sprite.width = 20;

           sprite.addChild(childShape);

           trace("After add a child, the height is:" + sprite.height);

           trace("After add a child, the width is:"  + sprite.width);

       }

Result: After add a child, the height is:0

After add a child, the width is:0

We see that the child DisplayObject has no impact on the width and height of the DisplayObject. This means that the height will not calculate the children nodes of it.

So here we have an conclusion: the height and width of an DisplayObject is not what it have drawn by itself, in another word: the content of DisplayObject does not contain the children of it.

3. About the relation between scaleX and width or scaleY and height

     In fact, the width and height is calculated with the scaleX, scaleY and the real position of it. We should remember that, after we adjust the width, in fact we have adjust the scaleX, the scaleX and scaleY is really stored.

posted @ 2011-03-12 22:42  lyqandgdp  阅读(248)  评论(0编辑  收藏  举报