題記
如我們iOS開(kāi)發(fā)者所知,目前iOS還沒(méi)有支持原生展現(xiàn)GIF圖片劫拗,因此合成和分解GIF圖片對(duì)于我們處理各種動(dòng)畫(huà)效果有著很高的使用價(jià)值间校。話不多說(shuō)先看看效果圖:
- 這里提供了3個(gè)按鈕,本質(zhì)上是兩個(gè)方法页慷,分解與合成GIF憔足,因?yàn)橹灰羞@兩個(gè)方法的存在,無(wú)論我們拿到的是GIF圖還是幀圖酒繁,我們都能簡(jiǎn)單地在我們的設(shè)備上播放GIF滓彰。
代碼
- 分解GIF
/// 把gif動(dòng)圖分解成每一幀圖片
///
/// - Parameters:
/// - imageType: 分解后的圖片格式
/// - path: gif路徑
/// - locatioin: 分解后圖片保存路徑(如果為空則保存在默認(rèn)路徑)
/// - imageName: 分解后圖片名稱
func decompositionImage( _ imageType: imageType, _ path: String, _ locatioin: String = "", _ imageName: String = "") {
//把圖片轉(zhuǎn)成data
let gifDate = try! Data(contentsOf: URL(fileURLWithPath: path))
guard let gifSource = CGImageSourceCreateWithData(gifDate as CFData, nil) else { return }
//計(jì)算圖片張數(shù)
let count = CGImageSourceGetCount(gifSource)
var dosc: [String] = []
var directory = ""
//判斷是否傳入路徑,如果沒(méi)有則使用默認(rèn)路徑
if locatioin.isEmpty {
dosc = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
directory = dosc[0] + "/"
}else{
let index = locatioin.index(locatioin.endIndex, offsetBy: -1)
if locatioin.substring(from: index) != "/" {
directory = locatioin + "/"
}else{
directory = locatioin
}
}
var imagePath = ""
//逐一取出
for i in 0...count-1 {
guard let imageRef = CGImageSourceCreateImageAtIndex(gifSource, i, nil) else { return }
let image = UIImage(cgImage: imageRef, scale: UIScreen.main.scale, orientation: .up)
//根據(jù)選擇不同格式生成對(duì)應(yīng)圖片已經(jīng)路徑
switch imageType {
case .jpg:
guard let imageData = UIImageJPEGRepresentation(image, 1) else { return }
if imageName.isEmpty {
imagePath = directory + "\(i)" + ".jpg"
}else {
imagePath = directory + "\(imageName)" + "\(i)" + ".jpg"
}
try? imageData.write(to: URL.init(fileURLWithPath: imagePath), options: .atomic)
case .png:
guard let imageData = UIImagePNGRepresentation(image) else { return }
if imageName.isEmpty {
imagePath = directory + "\(i)" + ".png"
}else {
imagePath = directory + "\(imageName)" + "\(i)" + ".png"
}
//生成圖片
try? imageData.write(to: URL.init(fileURLWithPath: imagePath), options: .atomic)
}
print(imagePath)
}
}
- 合成GIF
/// 根據(jù)傳入圖片數(shù)組創(chuàng)建gif動(dòng)圖
///
/// - Parameters:
/// - images: 源圖片數(shù)組
/// - imageName: 生成gif圖片名稱
/// - imageCuont: 圖片總數(shù)量
func compositionImage(_ images: NSMutableArray, _ imageName: String, _ imageCuont: Int) {
//在Document目錄下創(chuàng)建gif文件
let docs = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let gifPath = docs[0] + "/\(imageName)" + ".gif"
guard let url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, gifPath as CFString, .cfurlposixPathStyle, false), let destinaiton = CGImageDestinationCreateWithURL(url, kUTTypeGIF, imageCuont, nil) else { return }
//設(shè)置每幀圖片播放時(shí)間
let cgimageDic = [kCGImagePropertyGIFDelayTime as String: 0.1]
let gifDestinaitonDic = [kCGImagePropertyGIFDictionary as String: cgimageDic]
//添加gif圖像的每一幀元素
for cgimage in images {
CGImageDestinationAddImage(destinaiton, (cgimage as AnyObject).cgImage!!, gifDestinaitonDic as CFDictionary)
}
// 設(shè)置gif的彩色空間格式州袒、顏色深度揭绑、執(zhí)行次數(shù)
let gifPropertyDic = NSMutableDictionary()
gifPropertyDic.setValue(kCGImagePropertyColorModelRGB, forKey: kCGImagePropertyColorModel as String)
gifPropertyDic.setValue(16, forKey: kCGImagePropertyDepth as String)
gifPropertyDic.setValue(1, forKey: kCGImagePropertyGIFLoopCount as String)
//設(shè)置gif屬性
let gifDicDest = [kCGImagePropertyGIFDictionary as String: gifPropertyDic]
CGImageDestinationSetProperties(destinaiton, gifDicDest as CFDictionary)
//生成gif
CGImageDestinationFinalize(destinaiton)
print(gifPath)
}
- 播放
- 這里繼承UIImageView定義了一個(gè)JJGIFImageView類(lèi),增加了一個(gè)直接顯示GIF圖片的方法郎哭,只需要把GIF的路徑傳入他匪,設(shè)置GIF時(shí)間以及重復(fù)次數(shù)即可
class JJGIFImageView: UIImageView {
var images: [UIImage] = []
/// GIF圖片展示
///
/// - Parameters:
/// - path: GIF所在路徑
/// - duration: 持續(xù)時(shí)間
/// - repeatCount: 重復(fù)次數(shù)
public func presentationGIFImage(path: String, duration: TimeInterval, repeatCount: Int) {
decompositionImage(path)
displayGIF(duration, repeatCount)
}
private func decompositionImage(_ path: String) {
//把圖片轉(zhuǎn)成data
let gifDate = try! Data(contentsOf: URL(fileURLWithPath: path))
guard let gifSource = CGImageSourceCreateWithData(gifDate as CFData, nil) else { return }
//計(jì)算圖片張數(shù)
let count = CGImageSourceGetCount(gifSource)
//把每一幀圖片拼接到數(shù)組
for i in 0...count-1 {
guard let imageRef = CGImageSourceCreateImageAtIndex(gifSource, i, nil) else { return }
let image = UIImage(cgImage: imageRef, scale: UIScreen.main.scale, orientation: .up)
images.append(image)
}
}
private func displayGIF(_ duration: TimeInterval, _ repeatCount: Int) {
self.animationImages = images
self.animationDuration = duration
self.animationRepeatCount = repeatCount
self.startAnimating()
}
}