JoJo
JoJo

Reputation: 20115

Animate a UIView on a sine wave path

enter image description here

How would you make a UIView move along a sine wave path? Ideally, I'd be able to stop the animation when the UIView goes off the screen and release it. I see that UIView->animateWithDuration can only animate on one property at a time, but this seems like two exclusive things are happening simultaneously: it's moving to the right and it's moving up/down.

Upvotes: 3

Views: 6071

Answers (1)

paulvs
paulvs

Reputation: 12053

You can actually do this with a simple 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")
}

Upvotes: 8

Related Questions