Fade Animation for UIImages in Swift

北慕城南 提交于 2019-12-10 10:05:21

问题


I have a set of images that i would like to have fade in the background of my login screen. I cant find anything in swift that can do this. Is there a way that i would be able to?

Heres my current code:

override func viewDidLoad() {
    super.viewDidLoad()
    startAnimating()
    // Do any additional setup after loading the view, typically from a nib.
}

func startAnimating(){
    backgroundImage.animationImages = [
        UIImage(named: "background1.jpg"),
        UIImage(named: "background2.jpg")
    ]

    backgroundImage.animationDuration = 3
    backgroundImage.startAnimating()

}

回答1:


The below code will help you to animate image with fadeOut effect and change the background.

import UIKit

class ViewController: UIViewController {

    var imgView:UIImageView?  //class variable to display you bg image

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


        imgView = UIImageView(frame: self.view.frame) //imgView to display background
        self.view.insertSubview(imgView, atIndex: 0)  //imgview add above the background of main view

        animateImage(1) /*call animageImage with parameter number as image number as i user image name as avatar1.png, avatar2.png, avatar3.png and avatar4.png*/

    }


    func animateImage(no:Int)
    {
        var imgNumber:Int = no
        let t:NSTimeInterval = 1;
        let t1:NSTimeInterval = 0;
        var name:String = "avatar\(imgNumber).png"
        imgView!.alpha = 0.4
        imgView!.image = UIImage(named:name);

        //code to animate bg with delay 2 and after completion it recursively calling animateImage method 
        UIView.animateWithDuration(2.0, delay: 0, options:UIViewAnimationOptions.CurveEaseOut, animations: {() in 
                                                      self.imgView!.alpha = 1.0;
                                                   }, 
                                         completion: {(Bool) in
                                                      imgNumber++;
                                                      if imgNumber>4  //only for 4 image
                                                      {
                                                          imgNumber = 1
                                                      }
                                                      self.animateImage(imgNumber); 
                                                   })
    }
}


来源:https://stackoverflow.com/questions/25026621/fade-animation-for-uiimages-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!