本地gif的简单扩展。从gif获取所有图像,并将其添加到imageView animationImages。
extension UIImageView {
static func fromGif(frame: CGRect, resourceName: String) -> UIImageView? {
guard let path = Bundle.main.path(forResource: resourceName, ofType: "gif") else {
print("Gif does not exist at that path")
return nil
}
let url = URL(fileURLWithPath: path)
guard let gifData = try? Data(contentsOf: url),
let source = CGImageSourceCreateWithData(gifData as CFData, nil) else { return nil }
var images = [UIImage]()
let imageCount = CGImageSourceGetCount(source)
for i in 0 ..< imageCount {
if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
images.append(UIImage(cgImage: image))
}
}
let gifImageView = UIImageView(frame: frame)
gifImageView.animationImages = images
return gifImageView
}
}
使用方法:
guard let confettiImageView = UIImageView.fromGif(frame: view.frame, resourceName: "confetti") else { return }
view.addSubview(confettiImageView)
confettiImageView.startAnimating()
使用UIImageView API进行重复和持续时间自定义。
confettiImageView.animationDuration = 3
confettiImageView.animationRepeatCount = 1
完成gif动画后,要释放内存。
confettiImageView.animationImages = nil
animatedImageNamed()
不按照您的想法去做。该方法是加载了一系列静态图像的快捷方式被命名为喜欢这样image0
,image 1
,image2
等等,并将它们设置为animationImages
阵列。它不会像GIF一样加载动画图像。这个问题以前曾被问过,并给出了一些答案:stackoverflow.com/questions/9744682/display-animated-gif-in-ios-鉴于它不是Swift,但将答案应用于Swift并不难。