This guide will demonstrate one method for creating a repeating "flip book" or animated gif effect given multiple images. We will use a method, animatedImageWithImages()
that can be called on a UIImageView
in order to cycle through a collection of images at a duration that we will specify.
Make sure the images for your animation are all the same size.
We will hold our image animation in a UIImageView. It will need to be the same size as our image "frames".
UIImageView
class. HINT: A simple way is to just drag the first image "frame" on to the Storyboard from the Media Library at the bottom of the Utilities pane and it will automatically create an ImageView the correct size of your image frame. Instance Variables are declared below the class ViewController: UIViewController {
and above the override func viewDidLoad() {
var loading_1: UIImage!
var loading_2: UIImage!
var loading_3: UIImage!
We will need to store our images an array in order to easily reference them for our animation.
images
array. images
is plural because it will contain multiple images. [UIImage]!
means it will contain a collection of items, each item being of type, UIImage.var images: [UIImage]!
We will store our animated image into another variable of type UIImage.
var animatedImage: UIImage!
Assign values to the variables you declared above within the viewDidLoad()
method.
loading_1 = UIImage(named: "loading-1")
loading_2 = UIImage(named: "loading-2")
loading_3 = UIImage(named: "loading-3")
images
array.images = [loading_1, loading_2, loading_3]
animatedImageWithImages
method and store it in animatedImage
This method takes two arguments
animatedImage = UIImage.animatedImage(with: images, duration: 1.0)
animatedImage
.ImageView.image = animatedImage