iOS動畫進階 – 實現炫酷的上拉重新整理動效(二)| 掘金技術徵文

W_C__L發表於2019-03-02

最近擼了一個上拉重新整理的小輪子,只要遵循一個協議就能自定義自己動效的上拉重新整理和載入,我自己也寫了幾個動效進去,下面是一個比較好的動效的實現過程

先上效果圖和github地址,歡迎歡迎star,完整程式碼個demo和進入檢視,有其他好的動效大家也可以學習交流~

iOS動畫進階 – 實現炫酷的上拉重新整理動效(二)| 掘金技術徵文

分析動效

寫一個動效的第一步就應該仔細的去分析它,把它的每一幀展開來看,找一個最合適的方式來實現它,我們可以把以上動畫分解成以下三個步驟:

  1. 箭頭的繪製和動效
  2. 圓環的繪製和小點的旋轉
  3. 對勾的繪製和動畫

以下是會用到主要的類:

  • CAShapeLayer
  • UIBezierPath
  • CABasicAnimation
  • CAKeyframeAnimation
  • DispatchSourceTimer

箭頭的繪製和動效

剪頭的繪製我們用CAShapeLayer配合UIBezierPath來實現,把箭頭分解成兩個部分,一個是垂直的線和箭頭頭的部分,方便實現之後的動畫效果,下面是繪製主要的程式碼和效果圖:

iOS動畫進階 – 實現炫酷的上拉重新整理動效(二)| 掘金技術徵文

// 繪製垂直的線
private func initLineLayer() {
    let width  = frame.size.width
    let height = frame.size.height
    let path = UIBezierPath()
    path.move(to: .init(x: width/2, y: 0))
    path.addLine(to: .init(x: width/2, y: height/2 + height/3))
    lineLayer = CAShapeLayer()
    lineLayer?.lineWidth   = lineWidth*2
    lineLayer?.strokeColor = color.cgColor
    lineLayer?.fillColor   = UIColor.clear.cgColor
    lineLayer?.lineCap     = kCALineCapRound
    lineLayer?.path        = path.cgPath
    lineLayer?.strokeStart = 0.5
    addSublayer(lineLayer!)
}

// 繪製箭頭的頭部
private func initArrowLayer() {
    let width  = frame.size.width
    let height = frame.size.height
    let path = UIBezierPath()
    path.move(to: .init(x: width/2 - height/6, y: height/2 + height/6))
    path.addLine(to: .init(x: width/2, y: height/2 + height/3))
    path.addLine(to: .init(x: width/2 + height/6, y: height/2 + height/6))
    arrowLayer = CAShapeLayer()
    arrowLayer?.lineWidth   = lineWidth*2
    arrowLayer?.strokeColor = color.cgColor
    arrowLayer?.lineCap     = kCALineCapRound
    arrowLayer?.lineJoin    = kCALineJoinRound
    arrowLayer?.fillColor   = UIColor.clear.cgColor
    arrowLayer?.path        = path.cgPath
    addSublayer(arrowLayer!)
}複製程式碼

然後是箭頭動畫實現,我們分別對線和箭頭頭部進行動畫,通過CABasicAnimation對它們的strokeStartstrokeEnd進行控制來實現動畫,下面是效果圖和主要程式碼:

iOS動畫進階 – 實現炫酷的上拉重新整理動效(二)| 掘金技術徵文

// 箭頭的動畫
public func startAnimation() -> Self {
    let start = CABasicAnimation(keyPath: "strokeStart")
    start.duration  = animationDuration
    start.fromValue = 0
    start.toValue   = 0.5
    start.isRemovedOnCompletion = false
    start.fillMode  = kCAFillModeForwards
    start.delegate    = self
    start.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)

    let end = CABasicAnimation(keyPath: "strokeEnd")
    end.duration  = animationDuration
    end.fromValue = 1
    end.toValue   = 0.5
    end.isRemovedOnCompletion = false
    end.fillMode  = kCAFillModeForwards
    end.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)

    arrowLayer?.add(start, forKey: "strokeStart")
    arrowLayer?.add(end, forKey: "strokeEnd")

    return self
}

// 線的動畫
private func addLineAnimation() {
    let start = CABasicAnimation(keyPath: "strokeStart")
    start.fromValue = 0.5
    start.toValue = 0
    start.isRemovedOnCompletion = false
    start.fillMode  = kCAFillModeForwards
    start.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    start.duration  = animationDuration/2
    lineLayer?.add(start, forKey: "strokeStart")

    let end = CABasicAnimation(keyPath: "strokeEnd")
    end.beginTime = CACurrentMediaTime() + animationDuration/3
    end.duration  = animationDuration/2
    end.fromValue = 1
    end.toValue   = 0.03
    end.isRemovedOnCompletion = false
    end.fillMode  = kCAFillModeForwards
    end.delegate  = self
    end.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    lineLayer?.add(end, forKey: "strokeEnd")
}

// 通過delegate控制順序
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
    if flag {
        if let anim = anim as? CABasicAnimation {
            if anim.keyPath == "strokeStart" {
                arrowLayer?.isHidden = true
                addLineAnimation()
            }else {
                lineLayer?.isHidden = true
                animationEnd?()
            }
        }
    }
}複製程式碼

圓環的繪製和小點的旋轉

同樣的圓環和小點的繪製我們也可以用CAShapeLayer配合UIBezierPath來實現

,下面是效果圖和主要程式碼:

iOS動畫進階 – 實現炫酷的上拉重新整理動效(二)| 掘金技術徵文

// 繪製外環
private func drawCircle() {
    let width  = frame.size.width
    let height = frame.size.height
    let path = UIBezierPath()
    path.addArc(withCenter: .init(x: width/2, y: height/2), radius: height/2, startAngle: 0, endAngle: CGFloat(Double.pi * 2.0), clockwise: false)
    circle.lineWidth   = lineWidth
    circle.strokeColor = color.cgColor
    circle.fillColor   = UIColor.clear.cgColor
    circle.path        = path.cgPath
    addSublayer(circle)
    circle.isHidden = true
}

// 繪製小點
private func drawPoint() {
    let width  = frame.size.width
    let path = UIBezierPath()
    path.addArc(withCenter: .init(x: width/2, y: width/2), radius: width/2, startAngle: CGFloat(Double.pi * 1.5), endAngle: CGFloat((Double.pi * 1.5) - 0.1), clockwise: false)
    point.lineCap     = kCALineCapRound
    point.lineWidth   = lineWidth*2
    point.fillColor   = UIColor.clear.cgColor
    point.strokeColor = pointColor.cgColor
    point.path        = path.cgPath
    pointBack.addSublayer(point)
    point.isHidden = true
}複製程式碼

旋轉的實現,因為旋轉的速度是有個加速的效果的,所以我們使用DispatchSourceTimer來控制選擇的速度,下面是效果圖和主要程式碼:

iOS動畫進階 – 實現炫酷的上拉重新整理動效(二)| 掘金技術徵文

// 旋轉的控制
public func startAnimation() {
    circle.isHidden = false
    point.isHidden  = false

    codeTimer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
    codeTimer?.scheduleRepeating(deadline: .now(), interval: .milliseconds(42))
    codeTimer?.setEventHandler(handler: { [weak self] in
        guard self != nil else {
            return
        }
        self!.rotated = self!.rotated - self!.rotatedSpeed
        if self!.stop {
            let count = Int(self!.rotated / CGFloat(Double.pi * 2))
            if (CGFloat(Double.pi * 2 * Double(count)) - self!.rotated) >= 1.1 {
                var transform = CGAffineTransform.identity
                transform = transform.rotated(by: -1.1)
                DispatchQueue.main.async {
                    self!.pointBack.setAffineTransform(transform)
                    self!.point.isHidden  = true
                    self!.check?.startAnimation()
                }
                self!.codeTimer?.cancel()
                return
            }
        }
        if self!.rotatedSpeed < 0.65 {
            if self!.speedInterval < 0.02 {
                self!.speedInterval = self!.speedInterval + 0.001
            }
            self!.rotatedSpeed = self!.rotatedSpeed + self!.speedInterval
        }
        var transform = CGAffineTransform.identity
        transform = transform.rotated(by: self!.rotated)
        DispatchQueue.main.async {
            self!.pointBack.setAffineTransform(transform)
        }
    })
    codeTimer?.resume()

    addPointAnimation()
}

// 點的變化
private func addPointAnimation() {
    let width  = frame.size.width
    let path = CABasicAnimation(keyPath: "path")
    path.beginTime = CACurrentMediaTime() + 1
    path.fromValue = point.path
    let toPath = UIBezierPath()
    toPath.addArc(withCenter: .init(x: width/2, y: width/2), radius: width/2, startAngle: CGFloat(Double.pi * 1.5), endAngle: CGFloat((Double.pi * 1.5) - 0.3), clockwise: false)
    path.toValue = toPath.cgPath
    path.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
    path.duration = 2
    path.isRemovedOnCompletion = false
    path.fillMode = kCAFillModeForwards
    point.add(path, forKey: "path")
}複製程式碼

對勾的繪製和動畫

對勾的繪製我們也是用CAShapeLayer配合UIBezierPath來繪製,下面是效果圖和主要的程式碼:

iOS動畫進階 – 實現炫酷的上拉重新整理動效(二)| 掘金技術徵文

// 繪製對號
private func drawCheck() {
    let width = Double(frame.size.width)
    check = CAShapeLayer()
    check?.lineCap   = kCALineCapRound
    check?.lineJoin  = kCALineJoinRound
    check?.lineWidth = lineWidth
    check?.fillColor = UIColor.clear.cgColor
    check?.strokeColor = color.cgColor
    check?.strokeStart = 0
    check?.strokeEnd = 0
    let path = UIBezierPath()
    let a = sin(0.4) * (width/2)
    let b = cos(0.4) * (width/2)
    path.move(to: CGPoint.init(x: width/2 - b, y: width/2 - a))
    path.addLine(to: CGPoint.init(x: width/2 - width/20 , y: width/2 + width/8))
    path.addLine(to: CGPoint.init(x: width - width/5, y: width/2 - a))
    check?.path = path.cgPath
    addSublayer(check!)
}複製程式碼

對勾的動畫我們通過CAKeyframeAnimation來控制對勾的strokeStartstrokeEnd來實現對勾的動畫,下面是效果圖和主要程式碼:

iOS動畫進階 – 實現炫酷的上拉重新整理動效(二)| 掘金技術徵文

// 對勾的動畫
func startAnimation() {
    let start = CAKeyframeAnimation(keyPath: "strokeStart")
    start.values = [0, 0.4, 0.3]
    start.isRemovedOnCompletion = false
    start.fillMode = kCAFillModeForwards
    start.duration = 0.2
    start.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)

    let end = CAKeyframeAnimation(keyPath: "strokeEnd")
    end.values = [0, 1, 0.9]

    end.isRemovedOnCompletion = false
    end.fillMode = kCAFillModeForwards
    end.duration = 0.3
    end.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)

    check?.add(start, forKey: "start")
    check?.add(end, forKey: "end")
}複製程式碼

總結

關於小球的旋轉我沒有選擇CADisplayLink而是選擇的DispatchSourceTimer,是因為CADisplayLink會受到UITableview的影響,關於動畫的實現需要耐心去調細節,實現方式也各種各樣,大家如果有什麼更好的建議或者建議大家可以提出來~

完整的程式碼,大家可以去github地址去下載,歡迎大家star和發表意見和貢獻程式碼,有好的動效的話也可以提供,最後謝謝大家的閱讀

相關文章