如何布局CALayer

时间:2017-08-18 19:35:26

标签: swift macos calayer appkit caanimation

我有一个带有子图层的图层。子图层的位置是动画的。现在我希望当超级层的边界改变时,位置的动画可以适当地缩放,例如,超级层的宽度加倍,因此动画的距离也加倍。

我一直试图通过覆盖超级层的layoutSublayers()函数来实现这一点,并用新的缩放版替换旧动画。但是,在启动动画切换到全屏幕之前,向子图层添加新动画似乎会导致应用程序窗口冻结应用程序几秒钟。窗口的任何其他缩放都可以正常工作。 以下代码是我目前使用的代码:

override func layoutSublayers() {
    guard self.image != nil else { return }

    if var currentPosition = self.imageLayer.presentation()?.position {
        let relativeCurrentPosition = CGPoint(x: currentPosition.x / self.oldBounds.width, y: currentPosition.y / self.oldBounds.height)
        currentPosition = CGPoint(x: self.bounds.width * relativeCurrentPosition.x, y: self.bounds.height * relativeCurrentPosition.y)

        var targetPosition = (self.direction == .AtoB) ? self.positionB : self.positionB
        let relativeTargetPosition = CGPoint(x: targetPosition.x / self.oldBounds.width, y: targetPosition.y / self.oldBounds.height)
        targetPosition = CGPoint(x: self.bounds.width * relativeTargetPosition.x, y: self.bounds.height * relativeTargetPosition.y)

        if self.direction == .AtoB {
            self.positionA = currentPosition
            self.positionB = targetPosition
        } else {
            self.positionB = currentPosition
            self.positionA = targetPosition
        }

        let newPanAnimation = self.panAnimation
        newPanAnimation.duration = self.animationDuration - (CACurrentMediaTime() - self.timeAtImageStart)
        self.imageLayer.add(newPanAnimation, forKey: "pan")
    } else {
        CALayer.performWithoutAnimation {
            self.imageLayer.position = CGPoint(x: self.bounds.width / 2, y: self.bounds.height / 2)
        }
    }

    CALayer.performWithoutAnimation {
        self.imageLayer.bounds = self.originalImageLayerBounds
    }
}

这就是为什么我想知道什么是正确的方法,或者我可能已经走上了正确的道路而且只是存在不同的问题。

非常感谢!

0 个答案:

没有答案