先看下模擬器的效果
13.gif
gif圖其實也是一張張的圖片組合在一起,1s如果能播放15幀的話阳欲,人眼就不會感到明顯的卡頓临扮,一般電影院中的電影是一秒30幀,最近李安拍的新電影剃允,比利林恩是一秒120幀
- 我們使用系統(tǒng)一個框架ImageIO進行GIF圖播放沛简,大概思路是,首先把gif圖轉(zhuǎn)換成Data數(shù)據(jù)斥废,然后通過Data數(shù)據(jù)獲取到CGImageSource椒楣,然后通過這個CGImageSource獲取一幀一幀的畫面和總時間,然后用Image的動畫組進行播放
// MARK:- 播放gif圖
extension ViewController {
func playGifPic() {
// 1牡肉、找到gif捧灰,并且轉(zhuǎn)成data類型數(shù)據(jù)
guard let path = Bundle.main.path(forResource: "demo", ofType: "gif") else {
return
}
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 imgs = [UIImage]()
var totalDuaration: TimeInterval = 0
for i in 0..<imageCount {
// 3-1吩屹、從數(shù)組中取出圖片
guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, i, nil) else {
return
}
let image = UIImage(cgImage: cgImage)
if i==0 {
// 保存第一幀的圖
bjImg.image = image
}
imgs.append(image)
// 3-2、取出時間
guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) as? NSDictionary else {
return
}
guard let gifDict = properties[kCGImagePropertyGIFDictionary] as? NSDictionary else {
return
}
guard let frameDuration = gifDict[kCGImagePropertyGIFDelayTime] as? NSNumber else {
continue
}
totalDuaration += Double(frameDuration)
}
// 4拧抖、設置imageView的屬性
bjImg.animationImages = imgs
bjImg.animationDuration = totalDuaration
bjImg.animationRepeatCount = 1
// 5煤搜、播放
bjImg.startAnimating()
}
}