最近在自己的 side project 裡已經全面轉用 Swift。這篇文章把我在專案裡實作的一個 ActivityIndicator 視圖拆開來講,從需求拆解一路走到動畫驅動。
先看最終成果:

建議把 GitHub 上對應的完整專案抓下來,一邊看文章一邊對照程式碼會順很多。
目標是做一個功能上可以替代 UIActivityIndicatorView 的載入動畫,用 Core Graphics 自己畫出來,並讓它轉起來。
先把這個">.
圖形拆開:它由 8 段圓弧組成一圈。所以第一步得會畫圓弧:

接著畫出 8 段、均勻排成一圈:

最後靠循環改變每段圓弧的顏色,讓整圈「跑」起來。
我們繼承 UIView 並覆寫 drawRect,第一步取得當前繪圖上下文:
let context = UIGraphicsGetCurrentContext()
這裡用 UIBezierPath 建構路徑,再把路徑描邊繪製出來。
// 初始化一個 UIBezierPath 實例
let arcPath = UIBezierPath()
// 構建 Arc 路徑
arcPath.addArcWithCenter(CGPointMake(CGFloat(self.frame.size.width/2), CGFloat(self.frame.size.height/2)),
radius: CGFloat(Config.CC_ARC_DRAW_RADIUS),
startAngle: CGFloat(DegreesToRadians(startAngle)),
endAngle: CGFloat(DegreesToRadians(startAngle + Config.CC_ARC_DRAW_DEGREE)),
clockwise: true)
// 把路徑加入當前繪圖上下文
CGContextAddPath(context, arcPath.CGPath)
// 設定線寬
CGContextSetLineWidth(context, CGFloat(Config.CC_ARC_DRAW_WIDTH))
// 設定線色
CGContextSetStrokeColorWithColor(context, strokeColor)
// 描邊
CGContextStrokePath(context)
其中關鍵的建構方法是:
func addArcWithCenter(center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool)
參數意義分別是圓心座標、半徑、起始弧度、結束弧度,以及順時針或逆時針。
先把視圖尺寸、線寬、顏色等參數集中放進一個 Config 結構,方便日後調整:
struct Config {
static let CC_ACTIVITY_INDICATOR_VIEW_WIDTH = 40
static let CC_ARC_DRAW_PADDING = 3.0
static let CC_ARC_DRAW_DEGREE = 39.0
static let CC_ARC_DRAW_WIDTH = 6.0
static let CC_ARC_DRAW_RADIUS = 10.0
static let CC_ARC_DRAW_COLORS = [/* 八個由淺到深的灰色 CGColor */]
}
然後在 drawRect 裡用迴圈畫八次,每次推進起始角度並換上不同顏色:
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
var startAngle = Config.CC_ARC_DRAW_PADDING
for index in 1...8 {
let arcPath = UIBezierPath()
arcPath.addArcWithCenter(CGPointMake(CGFloat(self.frame.size.width/2), CGFloat(self.frame.size.height/2)),
radius: CGFloat(Config.CC_ARC_DRAW_RADIUS),
startAngle: CGFloat(DegreesToRadians(startAngle)),
endAngle: CGFloat(DegreesToRadians(startAngle + Config.CC_ARC_DRAW_DEGREE)),
clockwise: true)
CGContextAddPath(context, arcPath.CGPath)
startAngle += Config.CC_ARC_DRAW_DEGREE + (Config.CC_ARC_DRAW_PADDING * 2)
CGContextSetLineWidth(context, CGFloat(Config.CC_ARC_DRAW_WIDTH))
let colorIndex = abs(index - self.animateIndex)
let strokeColor = Config.CC_ARC_DRAW_COLORS[colorIndex]
CGContextSetStrokeColorWithColor(context, strokeColor)
CGContextStrokePath(context)
}
}
這裡的 self.animateIndex 用來記錄「顏色最淺那一格」目前落在哪個位置,再透過它與當前 index 的差值決定該段圓弧的顏色深淺。
既然要對標 UIActivityIndicatorView,至少該提供這三組 API:
func startAnimating() func stopAnimating() func isAnimating() -> Bool
實作策略很直觀:用一個 timer 週期性推進 animateIndex,並觸發重繪。
// 驅動顏色變化、產生動畫的索引
private var animateIndex: Int = 1
// 動畫用的 timer
private var animatedTimer: NSTimer?
// timer 回呼:讓 UIKit 重畫,並推進索引
@objc private func animate() {
if !self.hidden {
self.setNeedsDisplay()
self.animateIndex++
if self.animateIndex > 8 {
self.animateIndex = 1
}
}
}
// 開始動畫
func startAnimating() {
if self.hidden {
self.hidden = false
}
if let timer = self.animatedTimer {
timer.fire()
} else {
self.animatedTimer = NSTimer(timeInterval: 0.1, target: self,
selector: "animate", userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(self.animatedTimer!, forMode: NSRunLoopCommonModes)
}
}
值得留意的是,這裡刻意不用方便的那個寫法:
class func scheduledTimerWithTimeInterval(ti: NSTimeInterval, target aTarget: AnyObject, selector aSelector: Selector, userInfo: AnyObject?, repeats yesOrNo: Bool) -> NSTimer
而改用:
init(timeInterval ti: NSTimeInterval, target aTarget: AnyObject, selector aSelector: Selector, userInfo: AnyObject?, repeats yesOrNo: Bool)
原因是:scheduledTimerWithTimeInterval 會把 timer 直接掛進「當前」run loop,而當我們把這個 indicator 放在 UIScrollView 上時,使用者一開始拖動,主線程的 run loop mode 會切換成 UITrackingRunLoopMode,timer 就跟著停擺了。改成自己 addTimer 到 NSRunLoopCommonModes,才能讓它在各種 mode 下都持續觸發。
到這一步,畫面上應該已經跑出跟效果圖一致的動畫。但要真正做成一個「拿來就能用」的自訂元件,還有更多細節要補:初始化的多種入口、視圖被移除時的 timer 回收、intrinsicContentSize,以及要不要支援 @IBInspectable / @IBDesignable 讓使用者能在 storyboard 裡直接調整。完整程式碼與 Demo 可參考:https://github.com/yechunjun/CCActivityIndicatorView