Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Swift 實作筆記:為藍牙搜尋加上波紋擴散動畫

編輯:關於 Android 程式設計

最近手上的專案要處理藍牙連線與裝置掃描的互動。 scanning 的過程中如果畫面完全靜止,使用者其實很難判斷 App 到底有沒有在做事,所以我們決定在搜尋按鈕下方加上一圈圈向外擴散的波紋,讓「正在找」這件事變得看得見。

原本專案裡這段動畫是用 Objective-C 寫的,這篇筆記把它改寫成 Swift,順便整理成兩種常見的變化:一種是持續循環、永不停止的呼吸式波紋,另一種是點擊一次才放一圈、放完就消失的單次波紋。以下程式碼保留了原始專案的 Swift 2 語法風格,方便和舊專案對照。

做法一:持續向外擴散的循環波紋

這部分的重點是重寫繪圖方法 override func drawRect(rect: CGRect)。概念並不複雜:先決定要疊幾層波紋,接著用迴圈建立同數量的 CALayer,每層都畫同樣大小的圓形邊框,然後靠 CAAnimationGroup 讓它們「放大 + 淡出」,最後用 beginTime 把每一層的起始時間錯開,視覺上就會變成連續不斷的一圈圈漣漪。

關鍵參數只有兩個:pulsingCountT 決定同時存在幾圈,animationDurationN 決定一圈從生到死的時間。兩者相除就是每層之間的時間間隔。

let pulsingCountT:NSInteger = 4
let animationDurationN:Double = 4
let animationLayerR = CALayer.init()

for i in 0 ..< pulsingCountT {
    let pulsingLayer = CALayer.init()
    pulsingLayer.frame = CGRectMake(0, 0, rect.size.width, rect.size.height)
    pulsingLayer.borderColor = UIColor.redColor().CGColor
    pulsingLayer.borderWidth = 1
    pulsingLayer.cornerRadius = rect.size.height / 2

    let defaultCurveE = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionDefault)
    let animationGroupP = CAAnimationGroup.init()
    animationGroupP.fillMode = kCAFillModeBackwards
    // 讓每一層延遲不同的時間啟動,這是漣漪感的來源
    animationGroupP.beginTime = CACurrentMediaTime() + Double(i) * animationDurationN / Double(pulsingCountT)
    animationGroupP.duration = animationDurationN
    animationGroupP.repeatCount = HUGE
    animationGroupP.timingFunction = defaultCurveE

    let scaleAnimationN = CABasicAnimation.init(keyPath: "transform.scale")
    scaleAnimationN.fromValue = 1.4
    scaleAnimationN.toValue = 2.2

    let opacityAnimationN = CAKeyframeAnimation.init(keyPath: "opacity")
    opacityAnimationN.values = [1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0]
    opacityAnimationN.keyTimes = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]

    animationGroupP.animations = [scaleAnimationN, opacityAnimationN]
    pulsingLayer.addAnimation(animationGroupP, forKey: "plulsing")
    animationLayerR.addSublayer(pulsingLayer)
}
self.layer.addSublayer(animationLayerR)

這裡有兩個細節值得留意。第一,fillMode 設為 kCAFillModeBackwards,可以讓還沒轮到啟動的圖層先套用第一幀的樣子,避免開場時突然閃一下。第二,透明度用 CAKeyframeAnimation 逐段列出數值,而不是單純的 linear 淡出,這樣收尾會更自然一點。

把動畫掛到畫面上

繪圖完成後,建立一個自訂的 CircleView 承載波紋,再配一顆「開啟搜索」按鈕,點下去才把 CircleView 顯示出來:

// 承載波紋的圈視圖
circleV = CircleView.init()
circleV.frame = CGRectMake(100, 60, 100, 100)
circleV.hidden = true
circleV.backgroundColor = UIColor.clearColor()
self.view.addSubview(circleV)

// 類方法的呼叫方式,等同 Objective-C 裡的加號方法
CircleView.showLogStr()

// 觸發用的按鈕
let button1 = UIButton.init(frame: CGRectMake(100, 60, 100, 100))
button1.setTitle("開啟搜索", forState: .Normal)
button1.backgroundColor = UIColor.yellowColor()
button1.layer.cornerRadius = 50
button1.clipsToBounds = true
button1.setTitleColor(UIColor.blueColor(), forState: .Normal)
button1.addTarget(self, action: #selector(button1Click), forControlEvents: .TouchUpInside)
self.view.addSubview(button1)

// 點擊事件:把波紋顯示出來
func button1Click(btn: UIButton) {
    circleV.hidden = false
}

做法二:點一次,放一圈

第二種效果更輕量:它不是常駐的,而是每次觸發才產生兩個暫時的圖層,跑完兩秒後自動清掉。這裡借用了 Swift 的 extension 來擴充 UIView,作用等同 Objective-C 的 category,讓任何一個 View 都能直接呼叫這個方法。

實作上用 CAShapeLayer 配 UIBezierPath 畫出跟自身圓角一致的輪廓,然後同時做放大與淡出。內圈只畫描邊、外圈填色並墊在底層,兩層時間稍微錯開,看起來就比較有層次。最後用 dispatch_after 在兩秒後把圖層移除,避免節點無限累積。

// 參數一:圈的顏色;參數二:圈相對於 View 擴散的比例
func showCircleAnimationLayerWithColor(circleColor: UIColor, andScale aScale: CGFloat) {
    if (self.superview == false) && (circleColor == true) { return }

    let pathFrameE = CGRectMake(-CGRectGetMidX(self.bounds),
                               -CGRectGetMidY(self.bounds),
                               self.bounds.size.width,
                               self.bounds.size.height)
    let pathH = UIBezierPath.init(roundedRect: pathFrameE, cornerRadius: self.layer.cornerRadius)
    let shapePositionN = self.superview?.convertPoint(self.center, fromView: self.superview)

    // 內圈:只留描邊
    let circleShapeE1 = CAShapeLayer.init()
    circleShapeE1.path = pathH.CGPath
    circleShapeE1.position = shapePositionN!
    circleShapeE1.fillColor = UIColor.clearColor().CGColor
    circleShapeE1.opacity = 0
    circleShapeE1.strokeColor = circleColor.CGColor
    circleShapeE1.lineWidth = 0.6
    self.superview?.layer.addSublayer(circleShapeE1)

    let scaleAnimationN1 = CABasicAnimation.init(keyPath: "transform.scale")
    scaleAnimationN1.fromValue = NSValue.init(CATransform3D: CATransform3DIdentity)
    scaleAnimationN1.toValue = NSValue.init(CATransform3D: CATransform3DMakeScale(aScale, aScale, 1))
    scaleAnimationN1.duration = 2
    scaleAnimationN1.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionLinear)
    circleShapeE1.addAnimation(scaleAnimationN1, forKey: nil)

    let alphaAnimationN1 = CABasicAnimation.init(keyPath: "opacity")
    alphaAnimationN1.fromValue = 1
    alphaAnimationN1.toValue = 0
    alphaAnimationN1.duration = 1.8
    alphaAnimationN1.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseOut)
    circleShapeE1.addAnimation(alphaAnimationN1, forKey: nil)

    // 外圈:填色並墊在最底層
    let circleShapeE2 = CAShapeLayer.init()
    circleShapeE2.path = pathH.CGPath
    circleShapeE2.position = shapePositionN!
    circleShapeE2.fillColor = circleColor.CGColor
    circleShapeE2.opacity = 0
    circleShapeE2.strokeColor = UIColor.clearColor().CGColor
    circleShapeE2.lineWidth = 0
    self.superview?.layer.insertSublayer(circleShapeE2, atIndex: 0)

    let scaleAnimationN2 = CABasicAnimation.init(keyPath: "transform.scale")
    scaleAnimationN2.fromValue = NSValue.init(CATransform3D: CATransform3DIdentity)
    scaleAnimationN2.toValue = NSValue.init(CATransform3D: CATransform3DMakeScale(aScale, aScale, 1))
    scaleAnimationN2.duration = 2
    scaleAnimationN2.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionLinear)
    circleShapeE2.addAnimation(scaleAnimationN2, forKey: nil)

    let alphaAnimationN2 = CABasicAnimation.init(keyPath: "opacity")
    alphaAnimationN2.fromValue = 0.8
    alphaAnimationN2.toValue = 0
    alphaAnimationN2.duration = 1.7
    alphaAnimationN2.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseOut)
    circleShapeE2.addAnimation(alphaAnimationN2, forKey: nil)

    // 兩秒後定時清除,避免圖層堆積
    let timeE: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, 2 * Int64(NSEC_PER_SEC))
    dispatch_after(timeE, dispatch_get_main_queue()) {
        circleShapeE1.removeFromSuperlayer()
        circleShapeE2.removeFromSuperlayer()
    }
}

呼叫端就乾淨很多。第二顆按鈕刻意做成 120×60 的橢圓,用來示範非正圓的擴散效果:

let button2 = UIButton.init(frame: CGRectMake(100, 270, 120, 60))
// 依 width 與 height 的 1:2 比例建立橢圓視圖
button2.updateMaskToBounds(button2.bounds)
button2.setTitle("點擊", forState: .Normal)
button2.backgroundColor = UIColor.yellowColor()
button2.clipsToBounds = true
button2.setTitleColor(UIColor.blueColor(), forState: .Normal)
button2.addTarget(self, action: #selector(button2Click), forControlEvents: .TouchUpInside)
self.view.addSubview(button2)

func button2Click(btn: UIButton) {
    btn.showCircleAnimationLayerWithColor(UIColor.whiteColor(), andScale: 3)
}

兩種做法怎麼選

常駐型波紋適合「搜尋中」這種需要持續回饋的狀態,成本是永遠有一條動畫在跑;單次型波紋更像是點擊的回饋特效,用完即丟、不佔資源。專案裡其實兩者可以並存:按下按鈕的瞬間放一圈單次波紋當作觸發回饋,搜尋期間再讓常駐波紋接手。

效果如下圖:

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved