LoginSignup
12
11

More than 5 years have passed since last update.

UIBezierPathにCABasicAnimationでアニメーションをつける

Last updated at Posted at 2016-02-18

UIBezierPathはアニメーション可能ですが、いくつか嵌まったのでメモ。

  1. UIViewのdrawRectをオーバーライドするのではなく、CAShapeLayer()を作成し、そのpathプロパティにUIBezierPathのCGPath(これ忘れがち)を設定すること。
  2. CABasicAnimation(keyPath: "path")とやって pathを変化させることを教えてあげる。スペルミスをしても、なにもエラーを出してくれないので注意すること。(出す方法はあるのかな?)
  3. CABasicAnimationのformValueとtoValueにはUIBezierPathのCGPath(これ忘れがち)を指定する。型が不一致でもエラーをだしてくれないので注意すること。
    // 引数で指定されたポイントに円をアニメーションしながら書く

    private func drawGraphPoint(center: CGPoint){
        let radius = CGFloat(10.0) //円の半径の設定
        let myLayer = CAShapeLayer()
        self.layer.addSublayer(myLayer)

        let endCircle = UIBezierPath(arcCenter: center,
            radius: radius, 
            startAngle: 0.0,
            endAngle: CGFloat(2.0) * CGFloat(M_PI),
            clockwise: true)

        let startCircle = UIBezierPath(arcCenter: CGPointMake(/* アニメーションの開始位置を指定する */),
            radius: radius,
            startAngle: 0.0,
            endAngle: CGFloat(2.0) * CGFloat(M_PI),
            clockwise: true)

        myLayer.path = startCircle.CGPath // 型に注意!
        myLayer.lineWidth = 2
        myLayer.strokeColor = graphColor
        myLayer.fillColor = graphColor

        let animation = CABasicAnimation(keyPath: "path")

        animation.duration = duration //アニメーションの継続時間を指定する
        animation.fromValue = myLayer.path // 開始pathの設定
        animation.toValue = endCircle.CGPath // 終了pathの設定。型に注意!

        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) // animation curve is Ease Out
        animation.fillMode = kCAFillModeBoth // keep to value after finishing
        animation.removedOnCompletion = false // don't remove after finishing

        myLayer.addAnimation(animation, forKey: animation.keyPath)
    }

12
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
11