I had a great question from a teacher at a secondary school here in Ireland about animating images in a Swift Playground. The question was basically: How do I do it in a playground with Swift?
You can go to the source, of course, and check out the documentation, but I’ve added a new playground to our new Adventures feed to show off two ways (sort of) to display an animated image.
Our Adventures feed, for those of you just joining us, or who’ve forgotten, is aimed at slightly more advanced folks. It explores things like SwiftUI, UIKit in playgrounds, and more.
The PlaygroundBook: Animating Images
The new playground book is called Animating Images and shows you how to use some of the cool capabilities in
UIImageView to display a series of images over a certain amount of time.
The first page is an implementation of animated images using
UIImageView. We pass an array of images to a static method on
UIImage and set the duration over which they should be displayed. Play around with different numbers of images and duration to fine tune your animation. Make sure to read through the comments, which will show you other ways of using
The second page implements the same thing, but with SwiftUI. It cheats, a little bit. The
Image view that you would use to display images in SwiftUI doesn’t animate
UIImages that are animations. Try it out, instead of using our new
AnimatedImage view, comment that line out and add this line:
You’ll see a very static image that only displays our first image from the array. Our
AnimatedImage addition is simply a wrapper around UIKit’s
UIImageView. We could have used Combine or some other clever way to update our view with images. But this approach simply takes advantage of a well-known component we can re-use without too much pain.
Try it out, play around with your own images, your own timing, and see what kind of animated image you can create!
You can subscribe to our Adventures feed (or the original feed) here https://www.thecodehub.ie/playgrounds/ from your iPad. Alternatively, if you use Playgrounds on a Mac, you can paste this URL into the subscription bar: https://www.thecodehub.ie/playgrounds/adventures/feed.json