ajrlewis
ajrlewis

Reputation: 3058

Is it possible to fade between two view background images?

I would like to know if it's possible for some button to cause a fade from one background image to another? The following code I have results in an abrupt change from the current image, background-image-1, to the new image, background-image-2.

func buttonPressed() {
    if let image = UIImage(named: "background-image-2") {
        UIView.animateWithDuration(2, delay: 0, options: .CurveEaseInOut, animations: {_ in
            self.view.backgroundColor = UIColor(patternImage: image)
        }, completion: nil)
}

Thanks

EDIT

Though the accepted answer does work, I was finding slight glitches when toggling quickly between images. A similar method using UIView.animateWithDuration solves this:

func buttonPressed() {
    let oldImageView = UIImageView(image: UIImage(named: "background-image-1"))
    oldImageView.frame = view.frame
    let newImageView = UIImageView(image: UIImage(named:"background-image-2"))
    newImageView.frame = view.frame
    newImageView.alpha = 0
    view.insertSubview(newImageView, aboveSubview: backgroundImageView)
    view.insertSubview(oldImageView, aboveSubview: newImageView)
    UIView.animateWithDuration(1.0, delay: 0.0, options: .CurveEaseInOut, animations: {
        oldImageView.alpha = 0
        newImageView.alpha = 1
        }, completion: { completed in
            self.backgroundImageView.image = newImage
            newImageView.removeFromSuperview()
            oldImageView.removeFromSuperview()
    })
}

Upvotes: 7

Views: 2183

Answers (2)

Pranav Wadhwa
Pranav Wadhwa

Reputation: 7746

Say imageView is the UIImageView you are using for your animation. image1 is your original image. image2 is the new image. Try this:

let crossFade: CABasicAnimation = CABasicAnimation(keyPath: "contents")
crossFade.duration = 1
crossFade.fromValue = image1.CGImage
crossFade.toValue = image2.CGImage
self.imageView.image = image2
self.imageView.layer.addAnimation(crossFade, forKey: "animateContents")

Hope this helps.

Upvotes: 8

Duncan C
Duncan C

Reputation: 131481

The background color is supposed to be an animatable property, but a pattern color must not work.

Do you actually want a pattern color, or are you using that in order to insert an image as the background of the view without using the repeating pattern?

Upvotes: 0

Related Questions