Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to fade between two view background images?

Tags:

ios

swift

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()
    })
}
like image 626
alexjrlewis Avatar asked Apr 03 '16 22:04

alexjrlewis


People also ask

How do you fade a background image in CSS?

Syntax. filter: blur(px); To apply a blur effect to the background image, with the blur function use the z-index property to set the stack order of the element, set the width and height 100% to have a full background image.

What is crossfade css?

cross-fade() The cross-fade() CSS function can be used to blend two or more images at a defined transparency. It can be used for many simple image manipulations, such as tinting an image with a solid color or highlighting a particular area of the page by combining an image with a radial gradient.


1 Answers

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.

like image 191
Pranav Wadhwa Avatar answered Jan 02 '23 06:01

Pranav Wadhwa