UIView动画期间的中心位置

时间:2016-10-17 22:12:22

标签: ios swift uiview swift3 uiviewpropertyanimator

我想确定动画期间UIVIew(视图的中间点)的中心位置是什么。使用UIViewPropertyAnimator的动画如下:

let animator = UIViewPropertyAnimator(duration: 10, curve: .easeInOut)

var circle : UIView!
circle = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0))
circle.layer.cornerRadius = 20.0
circle.backgroundColor = UIColor.blue
self.view.addSubview(circle)

animator.addAnimations {
    circle.center = CGPoint(x: 100,y: 100)
    //or any other point
}
animator.startAnimation()

如果我在动画期间打印circle.center属性,那么我只得到动画的目标位置而不是真实位置。

Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true, block: {
[weak self] (Timer) -> Void in
if let circleCenterPosition = self?.circle.center
{
    print(circleCenterPosition)
}
})

在这次打印之后,我在控制台上看到了这个:

  

(100.0,100.0)

     

(100.0,100.0)

     

...

如何在动画期间打印实际位置?

感谢。

1 个答案:

答案 0 :(得分:2)

我想出了一个可能的答案。

CALayer有一个presentation()函数

  

func presentation()   返回表示层对象的副本,该副本表示当前在屏幕上显示的图层状态。

表示层有一个框架属性什么是CGRect,从这里可以轻松计算出中点。

演示

enter image description here

代码

class ViewController: UIViewController {
        var circle : UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let animator = UIViewPropertyAnimator(duration: 10, curve: .easeInOut)
        circle = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0))
        circle.layer.cornerRadius = 20.0
        circle.backgroundColor = UIColor.blue
        self.view.addSubview(circle)
        Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true)
        {
            [weak self] (myTimer) -> Void in
            if let movingBlueDotFrame = self?.circle.layer.presentation()?.frame
            {
                let blueDotOriginPoint = movingBlueDotFrame.origin
                let blueDotMiddlePoint = CGPoint(x: blueDotOriginPoint.x + movingBlueDotFrame.width/2, y: blueDotOriginPoint.y + movingBlueDotFrame.height/2)
                print(blueDotMiddlePoint)
                if blueDotMiddlePoint == CGPoint(x:100,y:100){
                    print("Yeeaahh")
                    myTimer.invalidate()
                }
            }
       }
        animator.addAnimations {
            self.circle.center = CGPoint(x: 100,y: 100)
        }
        animator.startAnimation()
    }
}

这个想法来自UIView animation determine center during animation

如果您有更简单或更好的解决方案,请在下面添加。谢谢!