问题
Relevant code below. I want each image to have a fade-in affect while they appear in the overall animation cycle. When running this code, the gif animation affect works, but the opacity changing code does not. Any help would be greatly appreciated. Thanks!
import UIKit
class View1: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var imagesNames = ["ALA0.jpeg", "ALA1.jpeg", "ALA2.png", "ALA3.png", "ALA4.png", "ALA5.png", "ALA6.png", "ALA7.png", "ALA8.png", "ALA9.png", "ALA10.png"]
var images = [UIImage]()
for i in 0..<imagesNames.count{
images.append(UIImage(named: imagesNames[i])!)
imageView.alpha = 0
UIImageView.animate(withDuration: 1.0) {
self.imageView.alpha = 1
}
}
imageView.animationImages = images
imageView.animationDuration = 6.0
self.imageView.startAnimating()
}
}
回答1:
Try below code: Updated
for i in 0..<imagesNames.count{
images.append(UIImage(named: imagesNames[i])!)
imageView.alpha = 0
UIImageView.animate(withDuration: 0.9, delay: 0, options: [UIViewAnimationOptions.curveEaseInOut,.repeat], animations: {
self.imageView.alpha = 1
}, completion: nil)
}
imageView.animationImages = images
imageView.animationDuration = 5 // I am using 5 images to perform animation
Note: From the above code.You will get a flashy effect frame to frame and you have to play with animation time duration and total animation duration to sync the effect.
回答2:
The problem is your animation is inside your for
loop.
You have 11 images, so the 4 lines that execute the animation, from imageView.alpha = 0
, are being executed 11 times, that's going to confuse the animation system.
You should set the alpha to 0 in the same place you set the animation images or the duration instead.
As for the actual animation, you should put that in viewDidAppear:
. You don't want your animation to start until the view is in the screen, otherwise it might seem like it doesn't start from the beginning.
Finally, a nicer way of instantiating the images array would be
let images = imageNames.flatMap { UIImage(named: $0) }
Even Swiftier, no need to declare all the names (Also, UIImage(named:)
will find the image extension for you, no need to add it.)
let images = (0..<11).flatMap { UIImage(named: "ALA\($0)") }
来源:https://stackoverflow.com/questions/40325884/how-to-change-opacity-of-animated-gif-images-in-ios