CoreAnimationのサンプル

雑にまとめます。 用語が一部正しくない場合がございます。

Pathに沿ってアニメーション

CAKeyframeAnimationにpositionで指定して、pathを指定してあげると パスに沿ってアニメーションします。

f:id:churabou:20190713215033g:plain

        let anim = CAKeyframeAnimation(keyPath: "position")
        anim.duration = 2
        anim.isRemovedOnCompletion = false
        anim.fillMode = .forwards
        anim.path = path.cgPath
        circleLayer.add(anim, forKey: nil)

https://gist.github.com/churabou/bcc3218df36018d345364eb5c18e537a#file-pathanimationview-swift

円形のチャートアニメーション

strokeEndを指定してあげるとPathのアニメーションをすることができます。

    let anim = CABasicAnimation(keyPath: "strokeEnd")
    anim.fromValue = 0
    anim.toValue = 1
    anim.duration = 1
    anim.isRemovedOnCompletion = false
    anim.fillMode = .forwards
    shapeLayer.add(anim, forKey: "key")

addArcメソッドで円を書く、そのパスをアニメーションさせます。 一つ下の階層に薄暗い背景のやつを表示することで円グラフのアニメーションができます。

     let path = UIBezierPath(
                    arcCenter: center,
                    radius: 100,
                    startAngle: -.pi / 2,
                    endAngle: .pi * 3 / 2,
                    clockwise: true
                )

f:id:churabou:20190713215026g:plain

https://gist.github.com/churabou/bcc3218df36018d345364eb5c18e537a

折れ線グラフの

点を決めてあげれば折れ線グラフのアニメーション

    let path = UIBezierPath()
    (0...10).forEach { i in 
        let point = CGPoint(x: CGFloat.random(in 0...1), y: CGFloat.random(in 0...1))
        i == 0 ? path.move(to: point) : path.addLine(to: point)
    }

f:id:churabou:20190713215030g:plain

 マスクアニメーション

CALayerをCAShapeLayerでmaskし、そのmaskのアニメーションをすることで、すでに描画してあるものを少しずつアニメーションしながら表示しています。

f:id:churabou:20190713215038g:plain

参考

チャートの色は適当に取ってきました。