iOS

iOS Programming 101: Simple Animation Using UIImageView


As you may know, we have released our first iOS game on App Store. Honestly, we do not have any game development experience. As we always said, “getting your hands dirty is the best way to learn programming”.

We started out by developing a simple memory game. We’re sure that it won’t be a big hit. However, it’s a great learning experience even the game do not generate good money. In coming tutorials, we’ll share with you some of the implementation techniques such as game center integration, in-app purchase implementation, Nextpeer integration for multiplayer support, etc. To start off, let’s see how you can use UIImageView to implement simple animation.

simple animation

UIImageView for Animations

In iOS, creating sophisticated animations does not require you to write complex code. The UIImageView class provides the easiest way for developers to implement animations. All you need to do is to create an UIImageView object with a series of images for animating. Once you trigger the animation, the image view will automatically render the individual frames. Cool, right?

Cartoon Images

Image series for animation

The UIImageView makes it very easy to implement simple animation. Let’s create a new Xcode project and see how it works.

Creating SimpleAnimation Project

First, fire up Xcode (make sure you’re using 4.6 or up) and create a new project using “Single View application” template.

Xcode Simple Animation Project

Create a new project using the Single View Application template

Click “Next” to continue. In reference to the below figure, fill in all the required values for the Xcode project. Make sure you enables the “Use Storyboards” option.

Xcode Simple Animation Project Settings

Simple Animation Project Settings

Click “Next” to continue. Xcode then asks you where you saves the “SimpleAnimation” project. Pick any folder (e.g. Desktop) to save your project.

Implementing the ViewController

Before implementing the ViewController class, first download the image pack which includes all images for creating the animation. Unzip the image pack and add all images to the SimpleAnimation project.

In the project navigator, select the “ViewController.m” and edit the “viewDidLoad” method with the following code:

That’s the code we need to create the animation. We first load all the images and save it into an array. We then create an UIImageView object and provide it with the image array as the value of animationImages. This array represents the “frames” of a dancing cartoon. You can control the frame rate by setting the animationDuration property. The property specifies the amount of time it takes to go through one cycle of the images. In the example, it takes 0.5 second to go through 16 images.

Optionally, you can also set the animationRepeatCount property, that specifies the number of times to repeat the animation. If it’s not set, the animation will be repeated indefinitely.

With all the properties configured, you can simply call up startAnimating method to begin animating the image. Compile and run the app to see how it works.

In order to give you a better idea about the animationDuration property, try to add a slow motion animation by adding the below code in the “viewDidLoad” method:

The above code will add another animation but with different animation duration. Compile and run the app again. Your app should look like this:

SimpleAnimation Deliverable

SimpleAnimation App

What’s Coming Next?

UIImageView provides a very easy way to implement interesting animation. Later, we’ll look into other ways to create visual effects. For your complete reference, you can download the whole Xcode project here.

As always, feel free to leave us comment and feedback. And don’t just read the tutorial. Remember to “get your hands dirty”. This is the best way to learn programming.

iOS
Adding Animated Effects to iOS App Using UIKit Dynamics
Tutorial
Building a Chatbot App for iOS with Dialogflow (API.AI) and Text-to-Speech
Tutorial
A Beginner’s Guide to Auto Layout with Xcode 10
  • David

    DavidDavid

    Author Reply

    Thanks for all! Your work is awesome! Thaks again!


  • Osvaldo Cipriano

    Thanks again for another tutorial.


  • Cenny

    CennyCenny

    Author Reply

    Great work, Love it!


  • Ren Glad

    Ren GladRen Glad

    Author Reply

    Thank u sooooooo much,pls continue this serials


  • Sangram Anand

    Thanks for the tuts..:)


  • Andrew Crowe

    How would u link animation start to button?
    and also how to link animation to stop on another button?


    • Ty Septiani

      that is easy. create the two buttons and link the IBAction to each button. Then inside each method of the button, for example, inside the method for start button, put the code “[animationImageView startAnimating];” and the same for the stop button. Hope this helps.


  • Ashish

    AshishAshish

    Author Reply

    nice one upload some more interesting animations


  • Ceylon Mobile

    nice thanks. i was wondering wht to put when my app is on Landscape mode. now i have grate thing to put. thanks again


  • Dennis Rubio

    Do you have the full tutorial on how you guys created the game? Would love to know. Thanks.


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      This is the only tutorial we published about the game. Later, we may release a guide for it.


  • JuanRa

    JuanRaJuanRa

    Author Reply

    Wonderful tutorial, thank you for posting it! I have a minor issue with my animation.. it lasts many frames, around 80, for the loop to complete, but i cant seem to be able to call more than 27 images on “NSArray *imageNames and it crashes when I run it, any thoughts?


  • Kishore Kumar

    It’s a great tutorial.u guys rock……….


  • hemanth

    hemanthhemanth

    Author Reply

    nice tutorial…. enjoy’d a lot. Please add more on animation,


  • HLA

    HLAHLA

    Author Reply

    i want to know that i can create the combo box like website combo box on app.


  • Splatush

    SplatushSplatush

    Author Reply

    Thanks! Everything is working great, but i just don’t know how to make it loop only once, can anyone help please?


    • 12Game2

      12Game212Game2

      Author Reply

      Yes, can someone please help, im having the same problem, i can’t find the “animationRepeatCount” property


  • Random Dude

    COOL! How do I add a picture to it


    • Random Dude

      i meant, how do i add a picture after the animation plays?


  • dirty man:D

    I’m feel so dirty now;) nice tutorial:)


  • James

    JamesJames

    Author Reply

    This tutorial is quite helpful. Currently, Flash (start from cs6) can export the animation movieclip to png sequence files. After that, we can use the same concept to create animation in ios. I write a IOS animation engine, it can help to animated png sequence file in a simple way. Here is the example: Create Animation in IOS Apps With PNG Sequence Files


  • Greg

    GregGreg

    Author Reply

    Thank you for the great tutorial! Very helpful.


  • acvivo

    acvivoacvivo

    Author Reply

    I like to use:

    UIImageView *animationImageView = [[UIImageView alloc] initWithImage:[UIImage animatedImageNamed:@”win_” duration:0.8]];

    It’s way less code.


  • montekaka

    montekakamontekaka

    Author Reply

    Thanks so much.

    Can we save add some sound with the animation and save the animation as video?


  • Ankit

    AnkitAnkit

    Author Reply

    How to show label with animation on button click..??


  • Deepak Kumar Arya

    How cud we get these image?


  • Manas Pathak

    just wonderful tutorial…it helps me lot…


  • JeanR

    JeanRJeanR

    Author Reply

    Would it be possible to control the speed of the animation with a bar (as for sound control) ?
    Would it be possible to make moving the animation in reverse order ?


  • Prateek

    PrateekPrateek

    Author Reply

    HUGE Memory issues with this method


    • jjmias

      jjmiasjjmias

      Author Reply

      Yeah I am noticing the same thing, how do we make this less of a memory hog?


      • Prateek

        PrateekPrateek

        Author Reply

        I dropped the memory foot print of the images. Convert to .jpeg or if you need the alpha layer use 16 bit textures. TexturePacker PNG Optimization with dithering is also a good bet if you own the product.. Also don’t forget to clear the array when your done with it. Or else it hogs the memory.


        • Mosterd

          MosterdMosterd

          Author Reply

          Hi, how do you clear the array?


          • Prateek

            PrateekPrateek

            Author

            set it as nil, remove all references.


  • Abhijit Joshi

    Great tutorial. Exactly what I was looking for. Thanks!


  • joeygrindsgears

    The NSArray is unnecessary. You could just directly add the images to the NSMutableArray because you already know the amount of images and the last image number:

    NSMutableArray *images = [[NSMutableArray alloc] init];

    for (int i = 0; i < NUM_OF_IMAGES; i++) {

    [images addObject:[UIImage imageNamed:[NSString stringWithFormat:@"win_%d.png", i]]];

    }

    NOTE: make sure NUM_OF_IMAGES is actually the number of total images you are including. Or for clarity, for (int i = 0; i <= NUM_OF_IMAGES – 1; i++) {…


    • Nick G.

      Nick G.Nick G.

      Author Reply

      This just saved my life, I have more than 300 images and I really don’t want to copy paste each of there names


      • joeygrindsgears

        anytime man. happy coding!


        • smartone2

          smartone2smartone2

          Author Reply

          sorry but when i tried your nsmutablearray option — i am getting this error

          “Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil’


          • smartone2

            smartone2smartone2

            Author

            figured it out
            )
            in the example in this page — the image (@”win_%d.png”) actually starts at 1 not 0 so the

            for (int i = 0; i < NUM_OF_IMAGES; i++)

            should be

            for (int i = 1; i < NUM_OF_IMAGES; i++)


          • joeygrindsgears

            Ah. You’re right. Edited. Thanks a lot and good luck.


    • Shanmugasundharam Selvadurai

      Thanks for the info


  • damodarbabu

    hi the tutorial is good for learning candiates and i want a clarification about if we give two animations i mean if i give two different images and for clicking one button i want to dialplay one type of related images as we took in the for loop condition and at the same time when we click another button we want to display another image in same layout how to do please clarify this is very important conecpt for each and every individual


  • BMac1435

    BMac1435BMac1435

    Author Reply

    How do I fix the picture size? When I run the simulator, the picture size and placement are not where I placed the UIImageView in my Storyboard.


  • Adam Hall

    Adam HallAdam Hall

    Author Reply

    This is completely obsolete now; as of iOS7 you can do everything above (as long as you follow a specific image naming convention) in one line of code.

    See http://stackoverflow.com/a/21911723/3166810


  • tom

    tomtom

    Author Reply

    The first time the animation runs, it “chugs”


  • Ashish

    AshishAshish

    Author Reply

    Thank you for taking the time to write this post. Very useful :).


  • krishan kumar Varshney

    i am doing same but for iPad running on iOS version 8.4 , memory consumption increases very rapidly from 35 Mb to 200 + Mb and finally leads to app crash


  • 吳易達

    吳易達吳易達

    Author Reply

    download link is lost.


Leave a Reply to Dennis Rubio
Cancel Reply

Shares