在 flex 中,我使用 VBox 和 HBox 来堆叠组件。当我尝试获取组件的 x,y 坐标时,我总是得到 0。如果我指定像 mx:VBox x="120" 这样的坐标,那么我得到的值。
如何在不明确说明的情况下获得坐标。
在 flex 中,我使用 VBox 和 HBox 来堆叠组件。当我尝试获取组件的 x,y 坐标时,我总是得到 0。如果我指定像 mx:VBox x="120" 这样的坐标,那么我得到的值。
如何在不明确说明的情况下获得坐标。
您可以将坐标相对于舞台进行平移。查看下面的代码:
var box:VBox = new VBox;
var child:DisplayObject = new DisplayObject;
box.addChild(child);
child.addEventListener(FlexEvent.UPDATE_COMPLETE, updateCompleteHandler);
...
private function updateCompleteHandler(fe:FlexEvent):void{
// find global coordinates
var globalCoords:Point = child.localToGlobal(new Point(0,0));
// coordsInBox is what you are looking for
var coordsInBox:Point = box.globalToLocal(globalCoords);
}
重点是localToGlobal
用于子组件,然后globalToLocal
转换全局坐标,以便它们相对于盒子容器表示。
UPDATE_COMPLETE
请注意,坐标在被子对象调用之前不会被处理。
The X and Y values of a component are always relative to the component's parent. directionsHelp.x
and directionsHelp.y
will both return the position relative to the VBox containing them which, unless you explicitly set the values or insert other components around it, will be 0 by default.
The thing to remember about localToGlobal()
is that you must call it from the child. If you have an Application
and you just call localToGlobal( new Point(child.x, child.y) )
, it will try to return the given point within the Application relative to the stage (because you haven't specified what "local" is), which will therefore conduct no transformations, and it will therefore stay equal to (0, 0).
If however you call child.localToGlobal( new Point(child.x, child.y) )
, it will return the value of the child's position relative to the stage, transforming the given point by however much the child is offset on the stage.
Here's a quick app to demonstrate:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" backgroundColor="#FFFFFF">
<mx:Script>
<![CDATA[
private function updateCoords():void
{
var point:Point = new Point(directionsHelp.x, directionsHelp.y);
point = directionsHelp.localToGlobal(point);
directionsHelp.text = "My stage coordinates are ("+point.x+", "+point.y+")";
}
]]>
</mx:Script>
<mx:VBox>
<mx:Box height="100" width="100" borderStyle="solid" borderColor="#000000"
horizontalAlign="center" verticalAlign="middle">
<mx:Label text="100 x 100" />
</mx:Box>
<mx:VBox>
<mx:Text id="directionsHelp" color="#4FA4CD" fontSize="8" fontWeight="bold"
text="Click the button to display my position on the stage." />
<mx:Button label="Get Position" click="updateCoords()" />
</mx:VBox>
</mx:VBox>
</mx:Application>