如何获取CAKeyframeAnimation对象的当前屏幕xy位置?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何获取CAKeyframeAnimation对象的当前屏幕xy位置?相关的知识,希望对你有一定的参考价值。

ios 12 beta 12下的Swift 4.2中,我想得到一个点的当前位置,我在CAKeyframeAnimation的路径上进行了动画处理。

动画的代码是这样的:

    @IBOutlet weak var dot: UIImageView!

    func animateDot()         
        // Oval path.
        let ovalWidth = UIScreen.main.bounds.width * 0.7
        let ovalHeight = UIScreen.main.bounds.height * 0.75
        let ovalPath = UIBezierPath(ovalIn: CGRect(x: -ovalWidth / 2 , y: -ovalHeight / 2, width: ovalWidth, height: ovalHeight))
        let orbit = CAKeyframeAnimation(keyPath: "position")
        orbit.path = ovalPath.cgPath
        orbit.duration = CFTimeInterval(2.5)
        orbit.isAdditive = true
        orbit.repeatCount = 6
        orbit.calculationMode = kCAAnimationPaced
        orbit.rotationMode = kCAAnimationRotateAuto

        self.dot.layer.add(orbit, forKey: "orbit")
    

我的问题是:一旦启动并运行,我怎样才能在Swift中查询动画以获得点中心的当前屏幕xy?

答案

我发现可以查询与点关联的活动表示层以获取绑定点的当前位置的帧:

        if (self.dot.layer.presentation() != nil)
        
            let dotLocation = self.dot.layer.presentation()?.frame
            os_log("self.dot.layer.presentation()?.frame.minX %12f", type: .debug, dotLocation!.minX)
            os_log("self.dot.layer.presentation()?.frame.maxX %12f", type: .debug, dotLocation!.maxX)
            os_log("self.dot.layer.presentation()?.frame.minY %12f", type: .debug, dotLocation!.minY)
            os_log("self.dot.layer.presentation()?.frame.maxY %12f", type: .debug, dotLocation!.maxY)

            var dotScreenLocation: CGPoint = CGPoint(x: 0, y: 0)
            dotScreenLocation.x = dotLocation!.minX + ((dotLocation!.maxX - dotLocation!.minX) / 2)
            dotScreenLocation.y = dotLocation!.minY + ((dotLocation!.maxY - dotLocation!.minY) / 2)
            os_log("self.dot.layer.presentation()?.frame center x,y %12f,%12f", type: .debug, dotScreenLocation.x, dotScreenLocation.y)

以上是关于如何获取CAKeyframeAnimation对象的当前屏幕xy位置?的主要内容,如果未能解决你的问题,请参考以下文章

在 Swift SceneKit 中使用 CAKeyframeAnimation 为 SCN 对象设置动画

OC动画:CAKeyframeAnimation

CAKeyframeAnimation 完成时如何指定选择器?

如何使用 CAKeyFrameAnimation 继续旋转视图?

如何在 Iphone 中停止 CAKeyFrameAnimation

如何同步几个不同图层的 CAKeyframeAnimation 动画?