iOS中GIF圖片的分解、合成與顯示

題記


如我們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()
    }
    
}


最后


附上GitHub的傳送門

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1、通過CocoaPods安裝項目名稱項目信息 AFNetworking網絡請求組件 FMDB本地數據庫組件 SD...
    陽明AGI閱讀 16,018評論 3 119
  • 十二月的中原初冬正濃,沒有生機的廟坪山大眼望去全是枯草,黃土,落葉交織的棕黃,少平走在從縣城到鄉下的碎石路上,心中...
    L右右閱讀 152評論 0 0
  • 今天又是高考的日子,對讀書人來說,就是走出校門的終極考驗。高考的基礎是必須讀書,不讀書,怎會遇上這樣的事? ...
    楊無涯閱讀 172評論 0 0
  • 轉載請注明出處:http://www.olinone.com/ 今天,跟大家聊聊“自釋放”思想在iOS開發中的應用...
    張群閱讀 334評論 0 2
  • 時常會聞到一種味道,溫暖質樸,讓人安心舒適。那是一種接近熱的大麥茶浮出的香氣,聞到這種味道時,總愿意閉上眼睛,微笑...
    April的秘密花園閱讀 254評論 0 2