Is it possible to fade between two background images?

I would like to know if it is possible for some button to cause fading from one background image to another? The following code that I have leads to a sharp change in the current background-image-1 to a new 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

Despite the fact that the accepted answer really works, I found slight glitches when quickly switching 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() }) } 
+5
source share
2 answers

Say imageView is the UIImageView that you use for your animation. image1 is your original image. image2 is a new image. Try the following:

 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.

+6
source

Background color is supposed to be an animated property, but the color of the template should not work.

Do you really need the color of the template, or do you use it to insert an image as the background of a view without using a repeating template?

0
source

Source: https://habr.com/ru/post/1246366/


All Articles