Swift5 オブジェクトのアニメーション

2019-08-24

画像などのUIViewをアニメーションかけた時に使用したものメモ。
参考APP

X/Yの移動

        UIView.animate(withDuration: 9, delay: 0.0, options: [.curveEaseInOut, .autoreverse, .repeat], animations: {
            self.cloudSImageView.center.x -= 200
        })
        UIView.animate(withDuration: 18, delay: 0.0, options: [.curveEaseInOut, .autoreverse, .repeat], animations: {
            self.cloudMImageView.center.x += 200
        })
        UIView.animate(withDuration: 25, delay: 0.0, options: [.curveEaseInOut, .autoreverse, .repeat], animations: {
            self.cloudLImageView.center.x += 200
        })
  • options 初動作やリピートなど追加可能
  • 上記は設定時間内に、200px移動する実装

回転

    lazy var circleAnimator = UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 10, delay: 0.0, options: [.curveLinear], animations: {
        UIView.setAnimationRepeatCount(100)
        self.circleImageView.transform = CGAffineTransform(rotationAngle: CGFloat.pi/180*180)
    })

    circleAnimator.startAnimation()
    circleAnimator.pauseAnimation()

回転の場合はrunningPropertyAnimatorを使う。
これは180°回転を繰り返して回ってるように見せる実装。
runningPropertyAnimatorのoptionsにはrepeatがないので、animation内でUIView.setAnimationRepeatCount(100)など書いてリピート処理をする。
なぜ360°を書かないかと言うと、そうしてしまうと360°= 0と見なされてしまい全く動かない実装になるのから。
他にも書き方があるので、これはそのうちの一つ。

# UILabel等に使えるアニメーションライブラリ
入力の際にアニメーションがかかるやつ
LTMorphingLabel