为了实现这个效果,能这样写:
UIView.animate(withDuration: 0.5, animations: { view.center.x += 200.0 }, completion: { _ in UIView.animate(withDuration: 0.5,animations: { view.center.y += 100.0}, completion: { _ in UIView.animate(withDuration: 0.5, animations: { view.center.x -= 200.0 }, completion: { _ in UIView.animate(withDuration: 0.5, animations: { view.center.y -= 100.0 }) })})})
这样写太麻烦了不是,有没更好的方法,当然有了,就是 Keyframe Animations 了。
我们能把飞机起飞的过程分为几个过程,前一阶段,飞机在跑道上加速;第二阶段,飞机向上倾斜爬升;第三阶段,飞机继续爬升,这次速率更快;第四阶段,动画的后 10% 部分,飞机飞出我们的视线,就像它飞进了云层中。
整体动画像上图那样。
现在用 Keyframe Animations 实现我们需要的效果,上代码:
func planeDepart() { let originalCenter = planeImage.center UIView.animateKeyframes(withDuration: 1.5, delay: 0.0, animations: { // add keyframes UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.25, animations: { self.planeImage.center.x += 80.0 self.planeImage.center.y -= 10.0 } ) }, completion: nil ) 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.1, relativeDuration: 0.4,第一个参数 0.1 代表从总动画时间的 10% 开始执行,第二个参数代表动画执行总时间。
效果示用意如下:
附:keyframe animations demo 下载
2018.06.25
上海 虹桥