【Swift】UIImageViewでアニメーション
どうも、ねこきち(@nekokichi1_yos2)です。
画像を連続で表示させる - アニメーションと言えば、GIF、が思い付きます。
しかし、GIFを作ろうとすると、
- 用意した画像をGIFに変換
- アニメーションを録画してGIFに変換
するなどの手間がかかります。
そこで、GIFを使わず、 UIImageだけでアニメーションを作る方法を書いていきます。
解説
手順は、下記の3つ。
- 画像を用意
- 画像を配列に入れる
- アニメーション開始
画像を用意
Assets.xcassetsに画像を全部突っ込みます。
↓

画像を配列に入れる
UIImageを格納できる配列を用意します。
↓
var images = [UIImage]()
用意した配列に画像を入れていきます。
↓
//アニメーションで流す画像を格納していく
for i in 1...6 {
images.append(UIImage(named: "image\(i).png")!)
}
(用意した画像の名前を統一すれば、たった数行で済むので、おすすめです。)
アニメーション開始
前提として、UIImageView(ここでは、image、の変数名)を用意してください。
アニメーションを開始するには、2つの方法があります。
まず1つ目。
//アニメーション用の画像を設定 image.animationImages = images //Duration:何秒以内にアニメーションをさせるか image.animationDuration = 3.0 //アニメーション開始 image.startAnimating()
アニメーションを止めるには、
image.stopAnimating()
を書くだけ。
(ただし、最初の画像から再びアニメーションが開始する)
また、
//Bool値
image.stopAnimating()
でアニメーション中かを判別可能。
そして、2つ目。
//Durationを指定、アニメーション開始 image.image = UIImage.animatedImage(with: images, duration: 5.0)
注意点として、停止できない..。
結果

ソースコード
import UIKit class ViewController: UIViewController { @IBOutlet weak var image: UIImageView! var images = [UIImage]() override func viewDidLoad() { //アニメーションで流す画像を格納していく for i in 1...6 { images.append(UIImage(named: "image\(i).png")!) } } @IBAction func start1(_ sender: Any) { //ポーズ中のみ if !image.isAnimating { image.animationImages = images image.animationDuration = 5.0 image.startAnimating() } } @IBAction func start2(_ sender: Any) { if !image.isAnimating { image.image = UIImage.animatedImage(with: images, duration: 5.0) } } @IBAction func pause(_ sender: Any) { //アニメーション中のみ if image.isAnimating { image.stopAnimating() } } }
参考