0

I have set up a couple of images that I need to automatically transition to the other and up till that point everything works great. Here is my code:

image1 = UIImage(named: "loginBg1.png")
image2 = UIImage(named: "loginBg2.png")

images = [image1, image2]
animatedImage = UIImage.animatedImage(with: images, duration: 3)
backgroundImageView.image = animatedImage

Now the thing is, I need them to fade when they transition. Basically I need to add a fade transition in between of the animation.

Also, if you have the experience I want to add a ken burns effect to the images as in it should pan/zoom on each image before transition and after.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
olbanana
  • 87
  • 3
  • 11

2 Answers2

1

Animating an image is not the same thing as transitioning. What you actually want to do is add an animation to the transition of displaying the second image. You do that with CATransition().

Check this answer for code: https://stackoverflow.com/a/9773674/2584110

Also, if you want a canned solution, try this github library: https://github.com/calm/KenBurns

It is a transition with Ken Burns effect.

Community
  • 1
  • 1
David Lari
  • 943
  • 11
  • 21
0

Here is a function that will fade out the current image and fade in a new image.

extension UIImageView{
    func transition(toImage: UIImage, withDuration duration: TimeInterval){
        UIView.animate(withDuration: duration, animations: {
            self.alpha = 0
        }) { (bool) in

            UIView.animate(withDuration: duration, animations: {
                self.image = toImage
                self.alpha = 1
            }, completion: nil)
        }
    }
}

The Ken Burns effect is more difficult. I suggest using a pod like this one: https://github.com/jberlana/JBKenBurns

Update:

Call the function like this:

let transitionToImage = UIImage.init(named: "newImage")! //newImage is the name of the Image Set in xcassets

let duration: TimeInterval = 1 //seconds, can also be fractions, i.e. 0.3, 0.5
imageView.transition(toImage: transitionToImage, withDuration: duration)
JB288
  • 96
  • 4
  • Hey thanks for this, but would you go a step further and tell me how to use this. I mean, I implemented the extension but how do I call this function? Will highly appreciate it, a newbie here. – olbanana Mar 16 '17 at 20:44
  • Appreciate your help, thank you! PS: For any one finding this, the images once called through this function goes out of scope, I think the constraints are not being applied. – olbanana Mar 17 '17 at 12:08