This repository has been archived by the owner on Jan 14, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 306
Extended use
Arne Bahlo edited this page Jan 16, 2016
·
1 revision
Read on if you want to achieve on of those things:
- Stop after n animations
- Run a function after n animations
For this, we need to use an UIImageView and add the images directly like this:
let jeremyGif = UIImage.gifWithName("jeremy")
let imageView = UIImageView(...)
// Uncomment the next line to prevent stretching the image
// imageView.contentMode = .ScaleAspectFit
// Uncomment the next line to set a gray color.
// You can also set a default image which get's displayed
// after the animation
// imageView.backgroundColor = UIColor.grayColor()
// Set the images from the UIImage
imageView.animationImages = jeremyGif?.images
// Set the duration of the UIImage
imageView.animationDuration = jeremyGif!.duration
// Set the repetitioncount
imageView.animationRepeatCount = 1
// Start the animation
imageView.startAnimating()
// CAKeyframeAnimation.values are expected to be CGImageRef,
// so we take the values from the UIImage images
var values = [CGImageRef]()
for image in jeremyGif!.images! {
values.append(image.CGImage!)
}
// Create animation and set SwiftGif values and duration
let animation = CAKeyframeAnimation(keyPath: "contents")
animation.calculationMode = kCAAnimationDiscrete
animation.duration = jeremyGif!.duration
animation.values = values
// Set the repeat count
animation.repeatCount = 1
// Other stuff
animation.removedOnCompletion = false
animation.fillMode = kCAFillModeForwards
// Set the delegate
animation.delegate = self
imageView.layer.addAnimation(animation, forKey: "animation")
In your class, you can now have a method like this, which get's called after the animation is complete.
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
if flag {
print("Animation finished")
}
}