您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

用 Swift 與 Core Animation 打造圓形圖片加載動畫

編輯:iOS 相關資訊

幾週前,Michael Villar 在他的 Motion 實驗系列裡做了一個很有意思的載入動畫:把一個圓形進度指示器與圓形揭露動畫結合在一起,效果獨一無二,還有點催眠。

本文要示範如何用 Swift 與 Core Animation 重現這個效果。完成之後,你可以依自己的設計語彙微調時間、曲線與顏色。

起點

先下載起始專案並執行,稍等片刻後你會看到一張圖片出現:

起始專案已經把視圖與載入邏輯準備好了:一個 ViewController、一個名為 CustomImageView 的 UIImageView 子類別,以及呼叫 SDWebImage 載入圖片的程式碼。

第一次執行時你會發現,圖片下載期間 App 幾乎停住不動,然後圖片才突然出現。這是因為目前完全沒有進度回饋——而這正是我們接下來要做的。

整個動畫分兩階段:

  1. 圓形進度:先畫出一個圓形進度指示器,並依下載進度更新它。
  2. 擴展圓形圖片:再讓一個圓形視窗擴張,把下載好的圖片揭露出來。

建立圓形指示器

先想清楚指示器的行為:一開始是空的,代表 0%,然後逐漸填滿直到下載完成。用 CAShapeLayer 並把路徑設為圓形,就能相當直覺地做到。

如果你對 CAShapeLayer 或 CALayer 的基本概念不熟,建議先看過 CALayer 的入門文章再回來。

CAShapeLayer 的 strokeStart 與 strokeEnd 控制描邊的起訖位置。把 strokeEnd 的值在 0 到 1 之間變化,就能對應到下載進度。

透過 iOS → Source → Cocoa Touch Class 建立一個新檔案,命名為 CircularLoaderView,父類別選 UIView。

點 Next 與 Create。這個 UIView 子類別接下來會容納所有動畫程式碼。

在 CircularLoaderView.swift 中加入屬性與常數:

let circlePathLayer = CAShapeLayer()
let circleRadius: CGFloat = 20.0

circlePathLayer 代表圓形路徑層,circleRadius 則是半徑。

接著加入初始化程式碼來配置 shape layer:

override init(frame: CGRect) {
    super.init(frame: frame)
    configure()
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    configure()
}

func configure() {
    circlePathLayer.frame = bounds
    circlePathLayer.lineWidth = 2
    circlePathLayer.fillColor = UIColor.clearColor().CGColor
    circlePathLayer.strokeColor = UIColor.redColor().CGColor
    layer.addSublayer(circlePathLayer)
    backgroundColor = UIColor.whiteColor()
}

兩個初始化方法都呼叫 configure()。configure() 把線寬設為 2、填色設為透明、描邊設為紅色,把 circlePathLayer 加入 view 的主 layer,最後把背景設為白色,讓圖片載入時螢幕其餘部分保持乾淨。

加上路徑

你會注意到目前 layer 還沒有 path。補上計算邊框的方法:

func circleFrame() -> CGRect {
    var circleFrame = CGRect(x: 0, y: 0, width: 2*circleRadius, height: 2*circleRadius)
    circleFrame.origin.x = CGRectGetMidX(circlePathLayer.bounds) - CGRectGetMidX(circleFrame)
    circleFrame.origin.y = CGRectGetMidY(circlePathLayer.bounds) - CGRectGetMidY(circleFrame)
    return circleFrame
}

這個方法回傳一個 CGRect,用來界定指示器的範圍:寬高各為 2 倍的半徑,並置於 view 的正中央。由於 view 尺寸改變時必須重新計算,把它獨立成一個方法比較好維護。

接著建立路徑本身:

func circlePath() -> UIBezierPath {
    return UIBezierPath(ovalInRect: circleFrame())
}

這裡回傳一個依 circleFrame() 範圍建立的 UIBezierPath。因為 circleFrame() 是正方形,所謂的「橢圓」最終會是一個正圓。

CALayer 沒有 autoresizingMask,所以必須在 layoutSubviews 裡手動更新 frame:

override func layoutSubviews() {
    super.layoutSubviews()
    circlePathLayer.frame = bounds
    circlePathLayer.path = circlePath().CGPath
}

frame 變了就要重新呼叫 circlePath() 觸發路徑重算,順序不能顛倒。

回到 CustomImageView.swift,把進度指示器作為屬性加入:

let progressIndicatorView = CircularLoaderView(frame: CGRectZero)

並在下載圖片的程式碼之前,於 init(coder:) 裡加上:

addSubview(self.progressIndicatorView)
progressIndicatorView.frame = bounds
progressIndicatorView.autoresizingMask = .FlexibleWidth | .FlexibleHeight

autoresizingMask 確保指示器永遠與 image view 同尺寸。

編譯執行,你會看到一個紅色的空心圓:

接下來要讓描邊長度隨下載進度變化。

改變描邊長度

回到 CircularLoaderView.swift,加入一個 computed property:

var progress: CGFloat {
    get {
        return circlePathLayer.strokeEnd
    }
    set {
        if (newValue > 1) {
            circlePathLayer.strokeEnd = 1
        } else if (newValue < 0) {
            circlePathLayer.strokeEnd = 0
        } else {
            circlePathLayer.strokeEnd = newValue
        }
    }
}

getter 直接回傳 circlePathLayer.strokeEnd;setter 會把輸入值夾在 0 到 1 之間,再寫回 layer。這個夾擠(clamp)是必要的,因為 strokeEnd 超出範圍會得到不可預期的繪圖結果。

在 configure() 裡初始化進度:

progress = 0

編譯執行,你會看到一片空白。這是對的:progress 為 0 意味著 strokeEnd 為 0,shape layer 什麼都沒畫。

回到 CustomImageView.swift,把 Update progress here 註解替換成:

self!.progressIndicatorView.progress = CGFloat(receivedSize)/CGFloat(expectedSize)

進度就是已接收位元組數除以總位元組數。

注意這裡的 block 使用 weak self 引用,目的是避免 retain cycle。

編譯執行,指示器開始隨下載推進而填滿:

有趣的是,你完全沒有寫任何動畫程式碼。CALayer 會自動偵測可動畫屬性,並在屬性變動時平滑地補上動畫——這就是 implicit animation。

第一階段完成,進入最後一階段。

建立揭露動畫

揭露階段要做的事:讓視窗顯示圖片,然後逐漸擴展圓環直到鋪滿整個畫面。這是 CALayer 的 mask 屬性非常漂亮的一個應用。

在 CircularLoaderView.swift 加入:

func reveal() {
    // 1
    backgroundColor = UIColor.clearColor()
    progress = 1

    // 2
    circlePathLayer.removeAnimationForKey("strokeEnd")

    // 3
    circlePathLayer.removeFromSuperlayer()
    superview?.layer.mask = circlePathLayer
}

逐段說明:

  1. 把背景設為透明,藏在後面的圖片才不會被遮住;同時把 progress 設為 1,也就是 100%。
  2. 移除 strokeEnd 上待處理的 implicit animation。若不移除,它會干擾後續的揭露動畫。
  3. 把 circlePathLayer 從原本的 superLayer 移開,改指派給 superview 的 layer.mask。這樣就能用這個圓形 mask 的「洞」把圖片露出來,同時複用既有的 layer,不必重複建立。

在 CustomImageView.swift 把 Reveal image here 註解替換為:

self!.progressIndicatorView.reveal()

編譯執行,圖片開始下載時會看到一個小圓環。你能在背景隱約看到圖片,但幾乎什麼都沒有——因為圓太小了。

讓圓環擴張

接下來要在內外同時擴張這個環。做法可以是建立兩個同心圓路徑,但有個更省事的方式:只動一個路徑,同時增加圓的半徑讓它向外擴,並增加線寬讓它向內擴。兩個值都長到足夠大時,整個圖片就露出來了。

回到 CircularLoaderView.swift,在 reveal() 最後補上:

// 1
let center = CGPoint(x: CGRectGetMidX(bounds), y: CGRectGetMidY(bounds))
let finalRadius = sqrt((center.x*center.x) + (center.y*center.y))
let radiusInset = finalRadius - circleRadius
let outerRect = CGRectInset(circleFrame(), -radiusInset, -radiusInset)
let toPath = UIBezierPath(ovalInRect: outerRect).CGPath

// 2
let fromPath = circlePathLayer.path
let fromLineWidth = circlePathLayer.lineWidth

// 3
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
circlePathLayer.lineWidth = 2*finalRadius
circlePathLayer.path = toPath
CATransaction.commit()

// 4
let lineWidthAnimation = CABasicAnimation(keyPath: "lineWidth")
lineWidthAnimation.fromValue = fromLineWidth
lineWidthAnimation.toValue = 2*finalRadius

let pathAnimation = CABasicAnimation(keyPath: "path")
pathAnimation.fromValue = fromPath
pathAnimation.toValue = toPath

// 5
let groupAnimation = CAAnimationGroup()
groupAnimation.duration = 1
groupAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
groupAnimation.animations = [pathAnimation, lineWidthAnimation]
groupAnimation.delegate = self
circlePathLayer.addAnimation(groupAnimation, forKey: "strokeWidth")

逐段說明這段程式碼:

  1. 先算出能完全覆蓋整個 view 的半徑(也就是 view 對角線的一半),再據此推出外擴後的矩形與最終路徑 toPath,它就是 mask 的最終形狀。
  2. 記錄 lineWidth 與 path 的起始值,等於目前 layer 的狀態。
  3. 把 lineWidth 與 path 直接設為最終值。這樣做是為了避免動畫結束後數值跳回原點。CATransaction 搭配 kCATransactionDisableActions 則是用來關掉 layer 的 implicit animation,否則這個「直接賦值」本身就會被動畫一次。
  4. 建立兩個 CABasicAnimation:一個動 path,一個動 lineWidth。lineWidth 必須增加到「兩倍的 finalRadius」,才能讓內縮速度與外擴速度一致,環看起來才是均勻變粗。
  5. 把兩個動畫放進 CAAnimationGroup 一起掛上 layer,duration 設為 1 秒,並指定 ease-in-ease-out 曲線。delegate 設為 self,等等會用到。

編譯執行,圖片下載完成後揭露動畫就會展開。但動畫結束後,畫面上還殘留著一點圓形。

修掉它,在 CircularLoaderView.swift 實作:

override func animationDidStop(anim: CAAnimation!, finished flag: Bool) {
    superview?.layer.mask = nil
}

把 mask 從 super layer 上移除,圓形就徹底消失了。

再次編譯執行,完整的動畫效果就出來了:

接著可以做什麼

你可以依需求微調動畫的時間、曲線與顏色。一個很值得嘗試的改進是把 shape layer 的 lineCap 設為 kCALineCapRound,讓進度指示器的尾端是圓頭而不是平頭,視覺上柔和很多。

想更深入學 Core Animation,可以參考 Marin Todorov 的 iOS Animations by Tutorials,它從基礎動畫出發,逐步帶到 layer animations、animating constraints 與 view controller transitions。

文章來源:Ray Wenderlich,作者:Rounak Jain

譯者簡介:劉耀柱(@Sam_Lau_Dev),iOS Developer 兼業餘 Designer,參與開發技術前線 iOS 項目翻譯,個人部落格:https://www.jianshu.com/users/256fb15baf75/latest_articles,GitHub:https://github.com/samlaudev。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved