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()
})
}
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With