
Swift很屌,開發(fā)自定義View可以說so easy。
大部分iOS初學(xué)者都會(huì)看斯坦福白胡子老頭的視頻, 講的確實(shí)挺好的。 在最新的iOS9第4課講了自定義UIView, 根據(jù)視頻寫個(gè)Demo,并使用定時(shí)器實(shí)現(xiàn)一個(gè)簡(jiǎn)單的動(dòng)畫。
自定義View動(dòng)畫的實(shí)現(xiàn)思路: 使用定時(shí)器或子線程每隔一段時(shí)間刷新一次界面, 界面重繪時(shí)要使用不同的參數(shù), 實(shí)現(xiàn)視覺上的動(dòng)畫效果, 其實(shí)就是幀動(dòng)畫。
先介紹一下定時(shí)器, 在iOS10版本里使用Timer類實(shí)現(xiàn)定時(shí)器的功能。 基本用法是
timer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true, block: { (param) in? /*注意param是Timer類型的參數(shù), 等于當(dāng)前Timer類實(shí)例的引用*/
self.count += 1? //自增1
let tmp: Double = Double(self.count) / 100.0? //畫嘴的角度
print("current mouthCur: \(tmp)")
self.faceView.mouthCurvature = tmp
self.faceView.setNeedsDisplay()? //UIView的方法, 即需要刷新view
//self.faceView.setNeedsLayout()
//self.faceView.layoutIfNeeded()
if self.count == 100 {
param.invalidate()? //停止定時(shí)器
}
print("counter current: \(self.count)")
})
在Android里自定義View會(huì)重寫onDraw函數(shù), 相當(dāng)于iOS UIView的的drawRect函數(shù)。 注意: drawRect不能直接被調(diào)用, 跟Android里不能指教調(diào)用onDraw方法一樣。 在自定義UIView時(shí), Xcode的注釋里已經(jīng)說明了drawRect函數(shù)的作用。
iOS的UIBezierPath類似于Android Canvas的drawLine/drawRect, 使用UIBezierPath可以繪制線條和圖形。 老頭在例子里也是使用UIBezierPath類繪制笑臉的。? iOS沒有畫布的概念, 設(shè)置顏色時(shí)直接使用UIColor類, 不像Android那樣使用Canvas的引用。
UIView繪制界面的方法:
override func draw(_ rect: CGRect) {
print("function draw is called")
// Drawing code
UIColor.blue.set()
pathForCircleCenterAtPoint(midPoint: skullCenter, withRadius: skullRadius)? //畫圓圈
UIColor.black.set()? //切換顏色, 顯示黑色眼睛
pathforEye(eye: .Left)? //畫左眼
pathforEye(eye: .Right)? //畫右眼
UIColor.red.set()
pathForMouth()
}
自定義UIView在預(yù)覽時(shí)默認(rèn)是空白的, 但Swift提供個(gè)關(guān)鍵字支持預(yù)覽自定義View。 僅僅需要再自定義UIView的上面加一行代碼@IBDesignable


最上面的gif動(dòng)畫是通過定時(shí)器修改mouthCurature參數(shù)改變嘴的形狀,Swift還支持使用@IBInspectable將自定義UIView的參數(shù)作為屬性, 在storyboard里預(yù)覽。 示例:


原文:http://blog.csdn.net/brycegao321/article/details/53817222
代碼下載地址: http://download.csdn.net/detail/brycegao321/9719939