[Swift]: Animate Image with UIImage

swift

05/09/2019


Animating image with a multiple image files in Swift 5

1) Import files

2) Create an outlet from UIImageView & an empty array of UIImage

SWIFT
// Animation image sets
@IBOutlet weak var diceSpiImageView: UIImageView!
var diceImages: [UIImage] = []

3) func to create an image array

SWIFT
func createImageArray(total: Int, imagePrefix: String) ->[UIImage] {
var imageArray: [UIImage] = []
for imageCount in 1...total {
let imageName = "\(imagePrefix)\(imageCount).png"
let image = UIImage(named: imageName)!
imageArray.append(image)
}
return imageArray
}
SWIFT
1...total

Be careful with a file name here
This includes fileName1.png ~ fileName{total}.png (inclusive)

4) Call the func created in 3)

SWIFT
override func viewDidLoad() {
super.viewDidLoad()
// total is number of images imported in 1)
diceImages = createImageArray(total: 39, imagePrefix: "diceSpin")
}

5) func to animate images

SWIFT
func animate(imageView: UIImageView, images: [UIImage]) {
imageView.animationImages = images
imageView.animationDuration = 0.3 // Duration of whole animation. 0.3 seconds
imageView.animationRepeatCount = 1
imageView.startAnimating()
}

6) Start animation of the UIImage

SWIFT
@IBAction func rollDiceBtn() {
animate(imageView: diceSpinImageView, images: diceImages)
}

+)


WRITTEN BY

Keeping a record