在正弦波路径上使UIView动画化

3

在此输入图片描述

如何使UIView沿正弦波路径移动?理想情况下,当UIView离开屏幕并释放时,我将能够停止动画。我看到UIView->animateWithDuration只能同时对一个属性进行动画处理,但这似乎是两个互斥的事情同时发生:它向右移动并上下移动。

1个回答

8
你可以使用简单的CAKeyframeAnimation来实现这一点。
override func viewDidLoad() {
    super.viewDidLoad()

    let myView = UIView(frame: CGRect(x: 10, y: 100, width: 50, height: 50))
    myView.backgroundColor = UIColor.cyan
    view.addSubview(myView)

    let animation = CAKeyframeAnimation()
    animation.keyPath = "position"
    animation.duration = 60  // 60 seconds
    animation.isAdditive = true // Make the animation position values that we later generate relative values.

    // From x = 0 to x = 299, generate the y values using sine.
    animation.values = (0..<300).map({ (x: Int) -> NSValue in
        let xPos = CGFloat(x)
        let yPos = sin(xPos)

        let point = CGPoint(x: xPos, y: yPos * 10)  // The 10 is to give it some amplitude.
        return NSValue(cgPoint: point)
    })
    myView.layer.add(animation, forKey: "basic")
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接