使用相同的 UIImageView 淡入淡出动画

Fade In & Out Animation With The Same UIImageView

我想知道是否可以使用相同的 UIImageView 创建任何类型的动画。每当用户单击按钮时,它都会使用淡入动画更改照片。

import UIKit

class ViewController: UIViewController {

var maximum: Int = 2
var number: Int = 0
var imageNames = ["0", "1"]

@IBOutlet weak var mainImage: UIImageView!
@IBOutlet weak var nextButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    // Gradient
    nextButton.setGradientBackground(colorOne: UIColor(red:0.00, green:0.78, blue:1.00, alpha:1.0), colorTwo: UIColor(red:0.00, green:0.45, blue:1.00, alpha:1.0))

    // Drop Shadows
    nextButton.layer.shadowColor = UIColor.black.cgColor
    nextButton.layer.shadowOffset = CGSize(width: 1, height: 1)
    nextButton.layer.shadowRadius = 25
    nextButton.layer.shadowOpacity = 0.10

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func changeImages(_ sender: Any) {
    number = Int(arc4random_uniform(UInt32(maximum)))
    mainImage.image = UIImage(named: "\(number).jpg")
}

}

我没有尝试创建动画。
我只是希望有人能帮我创建一个。

您可以尝试制作动画 alpha

@IBAction func changeImages(_ sender: Any) {
   number = Int(arc4random_uniform(UInt32(maximum)))
   mainImage.image = UIImage(named: "\(number).jpg")
   mainImage.alpha = 0
   UIView.animate(withDuration: 1.5, animations: {
     self.mainImage.alpha = 1
   }
}

您需要设置 alpha 值的动画。像这样制作淡入淡出功能:

 func fadeIn(){
    UIView.animate(withDuration: 3) {
        self.my.alpha = 0.0
    }
}

func fadeOut(){
    UIView.animate(withDuration: 3.0) {
        self.my.alpha = 1.0
    }
}

然后在更改图像时使用它:

fadeIn()
changeImages() /* your change image logic without animation */
fadeOut()