对于一些连续的动画,例如下面这种平移效果:
你可能会想到用前面学到的UIView.animate嵌套使用,做完后你会发现,你的代码嵌套了很多层,阅读和修改都不方便,这里有更好的实现方法,那就是关键帧动画
let originalCenter = planeImage.center
//withDuration:动画持续时间
//delay:动画延迟多少秒执行
UIView.animateKeyframes(withDuration: 1.5, delay: 0.0, animations: {
//add keyframes
//1.平移
//withRelativeStartTime:相对于withDuration的开始时间百分比,为0时表示动画开始时立刻执行
//relativeDuration:执行时间百分比,0.25表示执行1.5*0.25秒
UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.25, animations: {
self.planeImage.center.x += 80.0
self.planeImage.center.y -= 10.0
})
UIView.addKeyframe(withRelativeStartTime: 0.1, relativeDuration: 0.4) {
self.planeImage.transform = CGAffineTransform(rotationAngle: -.pi / 8)
}
UIView.addKeyframe(withRelativeStartTime: 0.25, relativeDuration: 0.25) {
self.planeImage.center.x += 100.0
self.planeImage.center.y -= 50.0
self.planeImage.alpha = 0.0
}
UIView.addKeyframe(withRelativeStartTime: 0.51, relativeDuration: 0.01) {
self.planeImage.transform = .identity
self.planeImage.center = CGPoint(x: 0.0, y: originalCenter.y)
}
UIView.addKeyframe(withRelativeStartTime: 0.55, relativeDuration: 0.45) {
self.planeImage.alpha = 1.0
self.planeImage.center = originalCenter
}
}, completion: nil)