3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CABasicAnimationで色のアニメーションがうまく行かないときの対処法

Posted at

アニメーション結果を保持するためにCAAnimation.isRemovedOnCompletionをtrueにするべきではない。
参考: How to not use isRemovedOnCompletion for CAAnimation in iOS

fillColorやstrokeColorを変更すると暗黙的アニメーション(implicit animation)が発生するため、CATransaction.setDisableActions(_:)を使用して暗黙的アニメーションを無効化してfillColorやstrokeColorを変更する必要がある。

CATransaction+Extensions.swift
import QuartzCore

extension CATransaction {
    /// 暗黙的アニメーション(implicit animations)が適用される変更をアニメーションなしで行うためのメソッド
    ///
    /// https://stackoverflow.com/a/54784013
    static func disableAnimations(_ completion: () -> Void) {
        CATransaction.begin()
        CATransaction.setDisableActions(true)
        completion()
        CATransaction.commit()
    }
}
example.swift
func animate() {
    let nextColor = UIColor.red.cgColor
    let animation = CABasicAnimation(keyPath: "fillColor")
    animation.fromValue = shapeLayer.fillColor
    animation.toValue = nextColor
    animation.duration = 2.0
    layer.add(animation, forKey: animation.keyPath)
    // アニメーションさせた後の状態を指定する
    // 自前のアニメーションが無効化されないようにfillColorやstrokeColorの暗黙的アニメーションを無効化して色を変更する
    CATransaction.disableAnimations {
        self.layer.fillColor = nextColor
    }
}
3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?