在正弦波路径上动画UIView
问题描述:
如何让UIView沿着正弦波路径移动?理想情况下,我可以在UIView关闭屏幕并释放它时停止动画。我发现UIView-> animateWithDuration一次只能在一个属性上进行动画制作,但这似乎是两个独有的事情同时发生的:它正在向右移动,并向上/向下移动。
答
你可以用简单的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")
}