簡要
上一篇使用UIView.animate
完成圖片堆疊
+淡入淡出
效果
但這比較算是土炮
方法
就像LeetCode
有千百種解法
所以我又去研究一下動畫方面的知識
發現later
裡面本來就有animate
今天就來看看animate怎麼實現一項的效果
基本設置
這邊我們簡單設置一個UIView
做示範
長寬
都是100
中間填空區先保留
等等下面會介紹CABasicAnimation
可以直接複製進來測試
let testView = UIView()
testView.frame = CGRect.init(x: 200, y: 200, width: 100, height: 100)
testView.backgroundColor = UIColor.darkGray
self.view.addSubview(testView)
/*
這裡是 CABasicAnimation 動畫區 下方會講解填空
*/
testView.layer.add(basicAnimation, forKey: nil)
CABasicAnimation
CABasicAnimation
特效非常多種
可以設定keyPath
轉換特效
我這邊測試了幾個常用特效
跟大家分享一下
旋轉
//旋轉
let basicAnimation = CABasicAnimation(keyPath: "transform.rotation.y")
basicAnimation.duration = 10
basicAnimation.repeatCount = 5
basicAnimation.fromValue = 0
basicAnimation.toValue = 2 * Double.pi
Demo
縮放
//縮放
let basicAnimation = CABasicAnimation(keyPath: "transform.scale")
basicAnimation.duration = 10
basicAnimation.repeatCount = 5
basicAnimation.fromValue = 0
basicAnimation.toValue = 2 * Double.pi
Demo
移動
//移動
let basicAnimation = CABasicAnimation(keyPath: "position")
basicAnimation.duration = 10
basicAnimation.repeatCount = 5
basicAnimation.fromValue = CGPoint.init(x: 100, y: 100)
basicAnimation.toValue = CGPoint.init(x: 400, y: 400)
Demo
閃爍
//閃爍
let basicAnimation = CABasicAnimation(keyPath: "opacity")
basicAnimation.duration = 0.2
basicAnimation.repeatCount = 10
basicAnimation.fromValue = 1.0
basicAnimation.toValue = 0.0
Demo
變色
//變色
let basicAnimation = CABasicAnimation(keyPath: "backgroundColor")
basicAnimation.duration = 0.2
basicAnimation.repeatCount = 10
basicAnimation.fromValue = UIColor.red.cgColor
basicAnimation.toValue = UIColor.blue.cgColor
Demo
圖片切換
圖片部分切換可以使用CABasicAnimation的contents
他就可以慢慢轉換成第二張圖片
我們這邊使用上一篇的buttonClicked事件
去實作圖片切換的動作
@IBAction func buttonClicked(sender: UIButton) {
let buttonTag = sender.tag
sender.tag = sender.tag + 1
let nextImage = UIImage.init(named: "food" + String(buttonTag))
let basicAnimation = CABasicAnimation(keyPath: "contents")
basicAnimation.fromValue = imageViewA.image?.cgImage
basicAnimation.toValue = nextImage?.cgImage
basicAnimation.duration = 1.5
imageViewA.layer.contents = imageViewA.image?.cgImage
imageViewA.layer.add(basicAnimation, forKey: nil)
imageViewA.image = nextImage
}
Demo
更方更簡單
物件使用更少
程式碼更簡化
大家可以試試看
prescription drug for stomach ulcers hypertension management in older adults gram negative bacilli uti treatment
phenergan online buy medications for ed ivermectin price comparison