題記
如我們iOS開發者所知,目前iOS還沒有支持原生展現GIF圖片,因此合成和分解GIF圖片對于我們處理各種動畫效果有著很高的使用價值。話不多說先看看效果圖:
- 這里提供了3個按鈕,本質上是兩個方法,分解與合成GIF,因為只要有這兩個方法的存在,無論我們拿到的是GIF圖還是幀圖,我們都能簡單地在我們的設備上播放GIF。
代碼
- 分解GIF
/// 把gif動圖分解成每一幀圖片
///
/// - Parameters:
/// - imageType: 分解后的圖片格式
/// - path: gif路徑
/// - locatioin: 分解后圖片保存路徑(如果為空則保存在默認路徑)
/// - imageName: 分解后圖片名稱
func decompositionImage( _ imageType: imageType, _ path: String, _ locatioin: String = "", _ imageName: String = "") {
//把圖片轉成data
let gifDate = try! Data(contentsOf: URL(fileURLWithPath: path))
guard let gifSource = CGImageSourceCreateWithData(gifDate as CFData, nil) else { return }
//計算圖片張數
let count = CGImageSourceGetCount(gifSource)
var dosc: [String] = []
var directory = ""
//判斷是否傳入路徑,如果沒有則使用默認路徑
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)
//根據選擇不同格式生成對應圖片已經路徑
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
/// 根據傳入圖片數組創建gif動圖
///
/// - Parameters:
/// - images: 源圖片數組
/// - imageName: 生成gif圖片名稱
/// - imageCuont: 圖片總數量
func compositionImage(_ images: NSMutableArray, _ imageName: String, _ imageCuont: Int) {
//在Document目錄下創建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 }
//設置每幀圖片播放時間
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)
}
// 設置gif的彩色空間格式、顏色深度、執行次數
let gifPropertyDic = NSMutableDictionary()
gifPropertyDic.setValue(kCGImagePropertyColorModelRGB, forKey: kCGImagePropertyColorModel as String)
gifPropertyDic.setValue(16, forKey: kCGImagePropertyDepth as String)
gifPropertyDic.setValue(1, forKey: kCGImagePropertyGIFLoopCount as String)
//設置gif屬性
let gifDicDest = [kCGImagePropertyGIFDictionary as String: gifPropertyDic]
CGImageDestinationSetProperties(destinaiton, gifDicDest as CFDictionary)
//生成gif
CGImageDestinationFinalize(destinaiton)
print(gifPath)
}
- 播放
- 這里繼承UIImageView定義了一個JJGIFImageView類,增加了一個直接顯示GIF圖片的方法,只需要把GIF的路徑傳入,設置GIF時間以及重復次數即可
class JJGIFImageView: UIImageView {
var images: [UIImage] = []
/// GIF圖片展示
///
/// - Parameters:
/// - path: GIF所在路徑
/// - duration: 持續時間
/// - repeatCount: 重復次數
public func presentationGIFImage(path: String, duration: TimeInterval, repeatCount: Int) {
decompositionImage(path)
displayGIF(duration, repeatCount)
}
private func decompositionImage(_ path: String) {
//把圖片轉成data
let gifDate = try! Data(contentsOf: URL(fileURLWithPath: path))
guard let gifSource = CGImageSourceCreateWithData(gifDate as CFData, nil) else { return }
//計算圖片張數
let count = CGImageSourceGetCount(gifSource)
//把每一幀圖片拼接到數組
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()
}
}