Following on from my Animated images on the iPhone post, i thought i’d take things a step further.
To re-cap, i pretty much summarised the available options for playing back simple animations on the iphone in this nice table:
| Method | Problem |
|---|---|
| Use UIImageView | It doesn't scale |
| Re-draw a UIView every frame | Far too slow |
| Use GLES | Beyond the scope of the last article, but not this one! |
| Transform a clipped UIView each frame | We did that last time |
To take things further, OpenGLES needs to be used. Specifically, you need to upload and draw a texture for every frame of your animation.
Now while this sounds like a great idea, there is a slight problem: uploading textures on the iPhone is hideously slow. Excluding the requirements of a video decoder, you only have enough time per frame to be able to playback a small stop motion video in RGB format.
All is not lost though. The iPhone supports two rather interesting texture formats: GL_COMPRESSED_RGB_PVRTC_* which is the native format, and GL_PALETTE* which is, as the name implies is a texture with a palette.
The fastest format to upload is PVR, but unfortunately there aren’t many native video codecs or animation formats about that decode to PVR format. Which leaves us with the palette format, which is just about fast enough to playback something more substantial…
Now which animation format uses a palette and is widely supported? Animated gif!
So to cut a long story short, i ended up writing a fairly elaborate library to decode and playback animated gifs on the iPhone, all in realtime.
Provided the gif is not gigantic (since the bigger the gif, the slower the decode + upload), it’s actually quite useable.
In fact, as a proof of concept i ended up writing an app using this library to playback animated gifs from any website in fullscreen (similar to the youtube app). Feel free to check it out - anim8gif.
The code
The code for this gif animation library, glgif, is located on github. As always, feel free to fork!