4
3

More than 1 year has passed since last update.

Swiftでフレーム毎にアニメーションさせる

Last updated at Posted at 2018-08-06

どうも、はぐっです・ω・♪

Swiftでアニメーションを行う

アニメーションの方法は様々

  • UIView.animate
  • CABasicAnimation
  • AutoLayoutとlayoutIfNeeded

とかとか。
その中で今回は、フレーム毎に値を計算してアニメーションさせる方法を紹介。

実装

早速、実装どーん!

private func setupLoop() {
    self.displayLink = CADisplayLink(target: self, selector: #selector(self.update))
    self.displayLink.preferredFramesPerSecond = 60 // 60fps
    self.displayLink.add(to: .current, forMode: .commonModes)
    self.displayLink.isPaused = false // ループスタート
}

@objc
private func update(displayLink: CADisplayLink) {
    // ここでアニメーション処理
}
    

アニメーションの手順

  • setupLoopでループ始める前に現在時刻を取得する
  • updateに入ってきた時の時刻との差で進捗状況を計算する
  • アニメーション対象のプロパティ(transform,opacity等)に、進捗状況に応じた値を入れる

こんな感じ!
進捗状況の計算にEasing使ったりすると、いい感じのアニメーションが作れるよ!

で、このままやと一生ループが走るから、止めたいタイミングで

self.displayLink.isPaused = true

として、ループを止めます。

いじょっ!

終わりに

今回はもろもろ割愛しますが、今回のような形のアニメーションにはTimerとかよりもCADisplayLinkの方が優秀かと。

めっちゃわたくしごとですが、jQueryではなく生のJavaScriptでアニメーションを実装したときもこんな形で実装していたので、とっつきやすかったですねー!

4
3
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
4
3