iOS提供了相应的核心动画类CABasicAnimation,CAKeyframeAnimation,我们可以通过设置这些类的相关属性来实现我们所需要的动画效果
首先,创建一个做动画的UIView
var myView = UIView()
myView.frame = CGRect(x: self.view.center.x - 100,y: 200,width: 200,height: 200)
myView.backgroundColor = UIColor.green
self.view.addSubview(myView)
设置CABasicAnimation动画
//缩放动画
let scaleAnimate = CABasicAnimation(keyPath: "transform.scale")
//起始帧
scaleAnimate.fromValue = 1.0
//结束帧
scaleAnimate.toValue = 1.5
//回放动画
scaleAnimate.autoreverses = true
//动画次数
scaleAnimate.repeatCount = MAXFLOAT
//动画时间
scaleAnimate.duration = 1.0
//旋转动画
let opaqueAnimate = CABasicAnimation(keyPath:"transform.rotation")
opaqueAnimate.fromValue = 0
opaqueAnimate.toValue = Double.pi * 2
opaqueAnimate.autoreverses = true
opaqueAnimate.repeatCount = MAXFLOAT
opaqueAnimate.duration = 1.0
//添加动画
myView.layer.add(scaleAnimate, forKey: "scaleAnimate")
myView.layer.add(opaqueAnimate, forKey: "rotationAnimate")
设置CAKeyframeAnimation动画
let keyAnimate = CAKeyframeAnimation(keyPath: "position")
//设置关键帧,动画的轨迹
let value0 = NSValue(cgPoint: myView.layer.position)
let value1 = NSValue(cgPoint: CGPoint(x: myView.layer.position.x, y: myView.layer.position.y + 200))
let value2 = NSValue(cgPoint: CGPoint(x: myView.layer.position.x - 150, y: myView.layer.position.y + 200))
let value3 = NSValue(cgPoint: CGPoint(x: myView.layer.position.x - 150, y: myView.layer.position.y))
let value4 = NSValue(cgPoint: myView.layer.position)
keyAnimate.values = [value0, value1, value2, value3, value4]
keyAnimate.autoreverses = false
keyAnimate.repeatCount = MAXFLOAT
keyAnimate.duration = 6.0
myView.layer.add(keyAnimate, forKey: "keyAnimate")
运行结果