動(dòng)畫: 圖片按照?qǐng)D中紅色軌跡線移動(dòng):

企業(yè)微信截圖_78de0b78-39bd-4060-b58c-f72cb0b88df9.png
位移關(guān)鍵幀動(dòng)畫: 運(yùn)動(dòng)關(guān)鍵點(diǎn)的方式制作位移動(dòng)畫; CAAnimationDelegate
import UIKit
// 遵循CAAnimationDelegate代理:
class ViewController: UIViewController, CAAnimationDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
yeAnimationForPath()
}
func yeAnimationForPath(){
// 顯示: 測(cè)試:
let imageView = UIImageView(frame: CGRect(x: 40, y: 120, width: 84, height: 84))
imageView.image = UIImage(named: "star")
self.view.addSubview(imageView)
//--- 9.20創(chuàng)建位移關(guān)鍵幀動(dòng)畫
/// 實(shí)例化一個(gè)關(guān)鍵幀動(dòng)畫, 可為層屬性指定關(guān)鍵路徑,以產(chǎn)生動(dòng)畫:
let animation = CAKeyframeAnimation(keyPath: "TyePosition")
animation.delegate = self
animation.duration = 5.0 //總時(shí)長(zhǎng) 5s;
// 動(dòng)畫路徑點(diǎn):
let point1 = CGPoint(x: 40, y: 120)
let point2 = CGPoint(x: 340, y: 120)
let point3 = CGPoint(x: 60, y: 360)
let point4 = CGPoint(x: 340, y: 360)
/// 創(chuàng)建動(dòng)畫的值數(shù)組:
animation.values = [NSValue(cgPoint: point1), NSValue(cgPoint: point2),
NSValue(cgPoint: point3), NSValue(cgPoint: point4)] //路徑點(diǎn);
/// 動(dòng)畫的關(guān)鍵點(diǎn)時(shí)間:
animation.keyTimes = [NSNumber(value: 0.0), NSNumber(value: 0.4),
NSNumber(value: 0.6), NSNumber(value: 1.0)] //到達(dá)對(duì)應(yīng)位置點(diǎn)的時(shí)長(zhǎng)比(0.4*5=2s:從第一個(gè)點(diǎn)到第二個(gè)點(diǎn)所花費(fèi)的時(shí)間);
/// 為視圖添加動(dòng)畫: 開始播放動(dòng)畫
imageView.layer.add(animation, forKey: "TyeMove")
}
// CAAnimationDelegate 代理方法:
func animationDidStart(_ anim: CAAnimation) {
print("--- 響應(yīng)動(dòng)畫開始的事件: --")
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
print("--- 響應(yīng)動(dòng)畫結(jié)束的事件: --")
}
}