众所周知,iOS并不是很好支持GIF图片,用的框架并不能很好支持,往往达不到想要的效果,下面介绍如何使用ImageIO实现GIF图片的加载,废话不多说,直接上代码
// 获取NSData类型
guard let filePath = Bundle.main.path(forResource: "demo.gif", ofType: nil) else { return }
guard let fileData = NSData(contentsOfFile: filePath) else { return }
// 获取Data获取CGImageSource对象
guard let imageSource = CGImageSourceCreateWithData(fileData, nil) else { return }
// 获取GIF中图片的个数和时间
let frameCount = CGImageSourceGetCount(imageSource)
var duration: TimeInterval = 0
var images: [UIImage] = [UIImage]()
for i in 0 ..< frameCount {
// 获取图片
guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, i, nil) else { continue }
let image = UIImage(cgImage: cgImage)
images.append(image)
// 获取时长
guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil), let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary] as? NSDictionary, let frameDuration = gifInfo[kCGImagePropertyGIFDelayTime] as? NSNumber else { continue }
duration += frameDuration.doubleValue
}
// 播放image
imageView.animationImages = images
imageView.animationDuration = duration
imageView.animationRepeatCount = 0
imageView.startAnimating()
此方法可以高度自定义加载GIF图片可以达到自己想要的效果,自定义重复次数,时长完全根据GIF本身时长而定