apache-flex 如何获取一个显示对象在祖先显示对象之间的总偏移量?

nx7onnlm  于 2022-11-01  发布在  Apache
关注(0)|答案(1)|浏览(130)

如何获得嵌套容器中的显示对象与根容器(如stage或spark Application)之间的距离?
例如:

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
                       xmlns:s="library://ns.adobe.com/flex/spark" 
                       xmlns:mx="library://ns.adobe.com/flex/mx"

                       applicationComplete="applicationCompleteHandler(event)"
                       >

    <fx:Script>
        <![CDATA[

            protected function applicationCompleteHandler(event:FlexEvent):void {
                var point:Point = new Point(nestedButton.x, nestedButton.y);
                var localToGlobalPoint:Point = this.localToGlobal(point);
                var globalToLocalPoint:Point = this.globalToLocal(point);
                var localToContentPoint:Point = this.localToContent(point);

                trace("Button x: " + nestedButton.x);
                trace("Button layout bounds x: " + nestedButton.getLayoutBoundsX());
                trace("Button to main container localToGlobal x: " + localToGlobalPoint.x);
                trace("Button to main container globalToLocal x: " + globalToLocalPoint.x);
                trace("Button to main container localToContent x: " + localToContentPoint.x);
            }

        ]]>
    </fx:Script>

    <mx:Canvas id="mainCanvas" top="10" left="10">
        <mx:Canvas top="10" left="10">
            <s:Group x="10" y="10">
                <s:Button id="sparkButton2" label="spark button" x=10 y="10"/>
            </s:Group>
        </mx:Canvas>
    </mx:Canvas>

</s:WindowedApplication>

如果按钮嵌套在3个容器中,每个容器距离前一个容器的边缘10像素,按钮距离其边缘10像素,则总的x值应该是40。这不是我得到的值。每个调用中的x值都跟踪到0

gudnpqoy

gudnpqoy1#

似乎没有Flash API可以实现这一点。因此,看起来像是您获取两个显示对象,并获得它们的全局位置,然后减去差值。
这里有一个函数,看起来它是有效的:

public function distanceBetweenDisplayObjects(source:Object, target:Object):Point {
    var sourceRelativePoint:Point;
    var sourceLocalToGlobalPoint:Point;
    var containerLocalToGlobalPoint:Point;
    var x:Number;
    var y:Number;

    var zeroPoint:Point = new Point(0, 0);
    sourceLocalToGlobalPoint = source.localToGlobal(zeroPoint);
    containerLocalToGlobalPoint = target.localToGlobal(zeroPoint);

    var sourceDifference:Point = sourceLocalToGlobalPoint.subtract(containerLocalToGlobalPoint);
    var containerDifference:Point = containerLocalToGlobalPoint.subtract(sourceLocalToGlobalPoint);

    return sourceDifference;
}

用法:

var sourceDifference:Point = distanceBetweenDisplayObjects(nestedButton, mainContainer);

相关问题