代码之家  ›  专栏  ›  技术社区  ›  1.21 gigawatts

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

  •  1
  • 1.21 gigawatts  · 技术社区  · 8 年前

    例如:

    <?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>
    

    10 从上一个和按钮边缘的像素 10 x 价值应该是 40 .这不是我得到的价值。这个 x 0 .

    1 回复  |  直到 8 年前
        1
  •  1
  •   1.21 gigawatts    8 年前

    似乎没有针对此的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);