封装播放GIF图片的
Imageview
分类
- GIF图片来源为本地或网络
- 导入系统库:
import ImageIO
- 加载本地GIF
func setGIFImage(gifname: String?) {
guard let name = gifname else { return }
guard let path = Bundle.main.path(forResource: name, ofType: nil) else { return }
guard let data = NSData(contentsOfFile: path) else { return }
guard let imageSource = CGImageSourceCreateWithData(data as CFData, nil) else { return }
playGIFWhit(imageSource)
}
- 加载网络GIF
func setGIFImage(urlString: String?) {
guard let urlStr = urlString else { return }
guard let url = URL(string: urlStr) else { return }
guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, nil) else { return }
playGIFWhit(imageSource)
}
- 播放GIF图
private func playGIFWhit(_ source: CGImageSource) {
let keyframeCount = CGImageSourceGetCount(source)
var images = [UIImage]()
var duration: TimeInterval = 0
for i in 0..<keyframeCount {
guard let cgimage = CGImageSourceCreateImageAtIndex(source, i, nil) else { continue }
guard let properties = CGImageSourceCopyPropertiesAtIndex(source, i, nil) ,
let giftInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
let keyframeDuration = giftInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber else { continue }
images.append(UIImage(cgImage: cgimage))
duration += keyframeDuration.doubleValue
}
self.animationImages = images
self.animationDuration = duration
self.animationRepeatCount = 0
self.startAnimating()
}
网友评论