以下は、これを行う方法を示すアプリケーションの例です。基本的な考え方は、ターゲット オブジェクト (ボタン) の座標を でグローバル座標に変換することlocalToGlobal()
です。次にglobalToLocal()
、グローバル座標を目的の座標空間に変換するために使用します。
最も重要なステップは最初の部分です。ボタンの座標をグローバル座標に変換するには、実際にはボタンの親を使用します。これは、ボタンが親の座標空間に「存在する」ためです。私がそれをするとき、これはいつも少し混乱します:)
このアプリを実行して遊んでください。実際にテストするには、「rootGroup」の周囲にもう 1 つ追加BorderContainer
し、「rootGroup」を数ピクセルだけオフセットして、ルートの座標空間がグローバル座標空間と同じにならないようにします。
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationComplete="onCreationComplete()">
<fx:Script>
<![CDATA[
private function onCreationComplete():void
{
var p:Point = new Point(childButton.x, childButton.y);
trace(p); // (x=50, y=50)
// convert the button's coordinates to Global coordinate space
// note since the button exists in the parent object's coordinate plane
// you do this conversion using the parent
var global:Point = parentGroup.localToGlobal(p);
trace(global); // (x=151, y=151) <-- 1 extra pixel from border of the BorderContainer
// now that we have global coordinates, use globalToLocal() to convert
// these coordinates into the desired coordinate plane
var rootLocal:Point = rootGroup.globalToLocal(global);
trace(rootLocal); // (x=151, y=151)
var parentLocal:Point = parentGroup.globalToLocal(global);
trace(parentLocal); // (x=50, y=50)
}
]]>
</fx:Script>
<s:BorderContainer id="rootGroup" borderColor="#FF0000">
<s:BorderContainer id="parentGroup" x="100" y="100" borderColor="#00FF00">
<s:Button id="childButton" x="50" y="50" label="Click Me"/>
</s:BorderContainer>
</s:BorderContainer>
</s:Application>