// 1.加載Gif圖片, 并且轉(zhuǎn)成Data類型
guard let path = Bundle.main.path(forResource: "demoGif.gif", ofType: nil)
guard let data = NSData(contentsOfFile: path) else { return }
// 2.從data中讀取數(shù)據(jù): 將data轉(zhuǎn)成CGImageSource對象
guard let imageSource = CGImageSourceCreateWithData(data, nil) else { return }
let imageCount = CGImageSourceGetCount(imageSource)
// 3.遍歷所有圖片
var images = [UIImage]()
var totalDuration : TimeInterval = 0
for i in 0..<imageCount {
? ? //取出圖片
guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, i, nil) else { continue }
let image = UIImage(cgImage: cgImage)
if i == 0 {
imageView.image = image
}
images.append(image)
? // 取出持續(xù)的時間
guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) as? NSDictionary else { continue }
guard let gifDict = properties[kCGImagePropertyGIFDictionary] as? NSDictionary else { continue }
guard let frameDuration = gifDict[kCGImagePropertyGIFDelayTime] as? NSNumber else { continue }
totalDuration += frameDuration.doubleValue
}
// 4.設(shè)置imageView的屬性
imageView.animationImages = images
imageView.animationDuration = totalDuration
imageView.animationRepeatCount = 0
// 5.開始播放
imageView.startAnimating()