ChenSmile
ChenSmile

Reputation: 3441

Swift - How to animate Images?

I'm trying to animate images in particular time- duration. It is working fine in Objective C. However, it is not working for Swift, where is my mistake?

The code for Objective-C is -

-(void)viewDidLoad
{
   [super viewDidLoad];
   NSMutableArray *imgListArray=[NSMutableArray array];
   for (int i=0; i<=11; i++)

   {
       NSString *strImageName=[NSString stringWithFormat:@"c%d.png", i];
       NSLog(@"%@",strImageName);
       UIImage *image=[UIImage imageNamed:strImageName];
       [imgListArray addObject:image];
   }

   self.imgView.animationImages = imgListArray;
   self.imgView.animationDuration =1.0f;    
   [self.imgView startAnimating];
   // Do any additional setup after loading the view, typically from a nib
}

The Code for swift is-

override func viewDidLoad()
{
   super.viewDidLoad()

   var imgListArray :NSMutableArray = []
   for countValue in 1...11
   {
      var strImageName : String = "c\(countValue).png"
      var image = UIImage(named:strImageName) // suggested by Anil
      imgListArray.addObject(image)
   }

   // Swift code HERE for Objective c
}

Upvotes: 24

Views: 54379

Answers (7)

winklerrr
winklerrr

Reputation: 14737

Swift 3+

UIImageViews can animate images in two different ways (the other answers already cover the first way in deep):

    • Create an [UIImage] array with the images to animate
    • Set the animationImages property of the view with this array
    • Set the animationDuration property
    • Start the animation

The following code uses #imageLiterals:

let images = [img1, img2, img3] // use of #imageLiterals here
let animation = UIImage.animatedImage(with: images, duration: 1)
self.myImageView.image = animation

Pro:

If you have to change the image of an UIImageView a lot and maybe one of those images should be animated, then you don't have to start/stop the animation every time anymore neither you need to set the animatedImages property back to nil to display the image stored in the image property of the image view.

Con:

You can't start/stop the animation, if it's encapsulated in a single UIImage instead of an array.


More on #imageLiterals:

If you want to use an image literal, either type imageLiteral or just type the name of an image from your assets folder and Xcode's code completion will suggest it.

Further reading:

  • Another good blog post about using #imageLiterals and #colorLiterals with animations to follow.

Upvotes: 5

Mili Shah
Mili Shah

Reputation: 1496

In swift 3 - Create Array of images and just animate that.

func animate_images()
{
    let myimgArr = ["1.jpg","2.jpg","3.jpg"]
    var images = [UIImage]()

    for i in 0..<myimgArr.count
    {
        images.append(UIImage(named: myimgArr[i])!)
    }

    imgView_ref.animationImages = images
    imgView_ref.animationDuration = 0.04
    imgView_ref.animationRepeatCount = 2
    imgView_ref.startAnimating()
}

And for stop animation just write

 imgView_ref.stopAnimating()

Upvotes: 14

Tiago Almeida
Tiago Almeida

Reputation: 14237

In swift you can go one step further and have a simple line to do this:

let loadingImages = (1...11).map { UIImage(named: "c\($0)")! }

Then you can do the rest and inject this into an imageView

self.imageView.animationImages = loadingImages
self.imageView.animationDuration = 1.0
self.imageView.startAnimating()

Upvotes: 19

Dave
Dave

Reputation: 12206

For anyone running multiple animations, depending on a variable, try the below.

For example, you could run an animation sending 0 or 1 (maybe based on if your app knows its daytime or nighttime):

func runAnimation (imgView: UIImageView, arrayPos: Int) {
    let timingArray = [7.0,10.0] //Durations of each
    let frameArray = [43,45]  //Frames for each
    var imgArray: Array<UIImage> = [] //Setup empty array 

    for i in 1 ... frameArray[arrayPos] {
        //Fill empty array with images!!
        let imageToAdd = UIImage(named: "animationNum_\(arrayPos)-frameNum_\(i)")
        imgArray.append(imageToAdd!)
    }
    imgView.animationImages = imgArray
    imgView.animationDuration = timingArray[arrayPos]
    imgView.animationRepeatCount = 2
    imgView.startAnimating()
}

Upvotes: 2

Jeffrey Neo
Jeffrey Neo

Reputation: 3809

for Swift 2, use [UIImage] instead.

var images: [UIImage] = []
for i in 1...2 {
    images.append(UIImage(named: "c\(i)")!)
}
myImageView.animationImages = images
myImageView.animationDuration = 1.0
myImageView.startAnimating()

Upvotes: 24

Michel Go&#241;i
Michel Go&#241;i

Reputation: 117

another approach if you want to animate an array of images:

var counter = 1
var timer = NSTimer()
@IBOutlet weak var someImg: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    timer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: Selector("doSomeAnimation"), userInfo: nil, repeats: true)
}

func doSomeAnimation() {
    //I have four pngs in my project, which are named frame1.png ... and so on


       if counter == 4 {

        counter = 1

        }else {

        counter++
    }

    someImg.image = UIImage(named: "frame\(counter).png")
}

Hope it helps!!

Upvotes: 2

Anil Varghese
Anil Varghese

Reputation: 42977

[UIImage imageNamed (strImageName)]

This not swift code. In swift it would be

UIImage(named:strImageName)  

Modified code:

var imgListArray :NSMutableArray = []
for countValue in 1...11
    {

        var strImageName : String = "c\(countValue).png"
        var image  = UIImage(named:strImageName)
        imgListArray .addObject(image)
    }

    self.imageView.animationImages = imgListArray;
    self.imageView.animationDuration = 1.0
    self.imageView.startAnimating()

Upvotes: 32

Related Questions