How to change opacity of animated gif images in iOS

a 夏天 提交于 2020-01-06 15:49:08

问题


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

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