Home > Software engineering >  How do I enable a .jpg image to fade in, in swift uiKit
How do I enable a .jpg image to fade in, in swift uiKit

Time:10-22

Good evening.

I downloaded a .jpg image and attached it through storyboard, and linked it to Home.swift. At this point, when I run the simulator the image is there. It does nothing at this time, but it's there.

I am trying to modify the code so that the image fades in when the simulator first runs. However, swift isn't liking my approach.

Much appreciate any guidance.

import Foundation

import UIKit

class Home: UIViewController {

    @IBOutlet var lonelinessLbl: UILabel! 

    @IBOutlet var Image: UIImageView!

    override func viewDidLoad() {

        super.viewDidLoad()

        startAnimations()

        // Do any additional setup after loading the view.

    }

    func startAnimations() {

        Image.animationImages = [

            UIImage(named: "birds.jpg")]

        Image.animationDuration = 3

        Image.startAnimations()   

    }    
}

CodePudding user response:

Inside startAnimations:

imageView.image = UIImage(named: "birds.jpg")
imageView.alpha = 0

UIViewPropertyAnimator(duration: 5.0, curve: .easeIn) {
  self.imageView.alpha = 1.0
}.startAnimation()

(Note that I've renamed Image to imageView -- the Swift convention is to name variables in camel case, starting with a lowercase letter)

CodePudding user response:

You can set the image to image view with animation. Use the extension to apply animation anywhere.

extension UIImageView{
    func setAnimatedImage(_ image: UIImage?) {
        UIView.transition(with: self, duration: 0.5, options: .transitionCrossDissolve, animations: {
            self.image = image
        }, completion: nil)
    }
}

Usage

yourImageView.setAnimatedImage(UIImage(named: "birds.jpg"))

CodePudding user response:

Setting an image array to animationImages only helps you when you have a set of images to animate it like a gif.

If you want to present animation like increasing alpha you can do the following.

override func viewDidLoad() {
    super.viewDidLoad()

    Image.alpha = 0.0
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    UIView.animate(withDuration: 0.3,
                   animations: {
                       self.Image.alpha = 1.0
                   },
                   completion: nil)
}
  • Related