LoginSignup
3
5

More than 5 years have passed since last update.

[Swift4.2]UIImageViewに回転アニメーション追加

Last updated at Posted at 2018-12-03

Activity Indicator がわりに画像を回転させてみました。

意外と簡単にできるんですね。
知らなかった。。。

ViewController.swift
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // 背景のグレー
        let grayView = UIView(frame: self.view.frame)
        grayView.backgroundColor = UIColor.gray
        self.view.addSubview(grayView)

        // 画像
        let image = UIImage(named: "moon") // 回したい画像
        let imageView = UIImageView(image: image)
        imageView.center = grayView.center
        grayView.addSubview(imageView)

        // アニメーション
        let rollingAnimation = CABasicAnimation(keyPath: "transform.rotation")
        rollingAnimation.fromValue = 0
        rollingAnimation.toValue = CGFloat.pi * 2.0
        rollingAnimation.duration = 2.0 // 周期2秒
        rollingAnimation.repeatDuration = CFTimeInterval.infinity // 無限に
        imageView.layer.add(rollingAnimation, forKey: "rollingImage") // アニメーションを追加

    }
}

処理終わったタイミングで画面を覆っているgrayViewごとremove してやれば良さそうです。

一応、全体のコードはこちらです。
https://github.com/HiroshiOshiro/RollingImageSample

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