【问题标题】:Animate a UIView on a sine wave path在正弦波路径上为 UIView 设置动画
【发布时间】:2016-06-12 00:31:26
【问题描述】:

如何让 UIView 沿着正弦波路径移动?理想情况下,当 UIView 离开屏幕并释放它时,我能够停止动画。我看到 UIView->animateWithDuration 一次只能在一个属性上设置动画,但这似乎同时发生了两件事:向右移动和向上/向下移动。

【问题讨论】:

    标签: ios cocoa-touch animation


    【解决方案1】:

    您实际上可以使用简单的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")
    }
    

    【讨论】:

      猜你喜欢
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-22
      • 1970-01-01
      • 1970-01-01
      • 2013-09-08
      相关资源
      最近更新 更多