環形進度條常用 CAShapeLayer 繪製。先建立一個完整的圓形路徑,再透過 strokeStart 與 strokeEnd 控制進度起點與終點。若要讓進度變化有動畫,可以使用 CATransaction 包住 strokeEnd 的更新。
progressLayer.strokeStart = 0
progressLayer.strokeEnd = CGFloat(progress) / 100.0
加入動畫時,可以設定動畫時間與節奏曲線。
CATransaction.begin()
CATransaction.setAnimationDuration(duration)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: .easeInEaseOut))
progressLayer.strokeEnd = CGFloat(progress) / 100.0
CATransaction.commit()
若希望進度條前端有一個圓點,可以建立一個小 UIView 或 CAShapeLayer,並讓它沿著圓弧移動。這裡可以使用 CAKeyframeAnimation,把圓點的位置綁定到進度對應的路徑上。
實作時,通常會先根據目前進度計算圓弧上的座標,再讓圓點在 setProgress 時移動到新的位置。
如果要在進度條頭部放箭頭,讓它始終朝向前進方向,可以把 CAKeyframeAnimation 的 rotationMode 設為 kCAAnimationRotateAuto。
orbit.rotationMode = kCAAnimationRotateAuto
這樣當進度增加或減少時,箭頭會自動旋轉到對應方向,而不需要手動計算角度。
若要讓進度條可以在 Interface Builder 中使用,可以把元件標記為 @IBDesignable,並把 progress 標記為 @IBInspectable。如此就能直接在 storyboard 或 xib 中預覽與調整初始值。
基礎版只需要 CAShapeLayer 與 strokeEnd;進階版則可以加上圓點、箭頭、陰影與路徑動畫。若需要更細緻的視覺效果,也可以再延伸加入漸層、光暈或自訂路徑。