iOS 分析一個支持GIF的UIImage擴展:SwiftGIF


Github:https://github.com/bahlo/SwiftGif

 

這個extension代碼不多,主要通過Apple的ImageIO框架進行解析GIF。

整個擴展最核心還是下面的函數,搞了半天還是Apple的UIImage的類函數。所以重點就是找到GIF中的每一幀圖片和每一幀的延遲是多少。

只要通過該函數返回的UIImage就是一個帶動畫的UIImage(記得我當年切了幾個圖還新建NSTimer實現動畫…)

可見會調用API的重要性…

let animation = UIImage.animatedImageWithImages(frames,duration: Double(duration) / 1000.0)

 

大致過程如下:

1.imageName.GIF文件 -> NSData

contentsOfURL函數:

 

2.NSdata -> CGImageSource

CGImageSourceCreateWithData函數

 

3.從CGImageSource的對象中取得圖片張數

CGImageSourceGetCount(source)

 

4.創建CGImage類型的數組,將CGImageSource中的圖片一張張的添加到該數組中

CGImageSourceCreateImageAtIndex(source, i, nil)

 

5.創建delay數組,將CGImageSource中的每一幀的圖片的延遲加入數組,這個函數比較麻煩

先是取得CGImageSource中的某個實體,類型是CFDictionary:

        let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil)

然后取得該字典中的Gif類型的字典,類型是CFDictionaryRef(CFDictionary的引用,是一樣的)

    let gifProperties: CFDictionaryRef = unsafeBitCast(

            CFDictionaryGetValue(cfProperties,

                unsafeAddressOf(kCGImagePropertyGIFDictionary)),

            CFDictionary.self)
然后從GIF字典中取得延遲時間,這里取2次,先是嘗試了kCGImagePropertyGIFUnclampedDelayTime,再嘗試kCGImagePropertyGIFDelayTime:

var delayObject: AnyObject = unsafeBitCast(

            CFDictionaryGetValue(gifProperties,

                unsafeAddressOf(kCGImagePropertyGIFUnclampedDelayTime)),

            AnyObject.self)

if delayObject.doubleValue == 0 {

            delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties,

                unsafeAddressOf(kCGImagePropertyGIFDelayTime)), AnyObject.self)

        }

 

6.這樣大概就按順序構建起了2個數組,一個是CGImage數組,一個是延遲大小。

7.然后把CGImage的數組轉成UIImage的數組,因為UIImage.animatedImageWithImages(frames,duration)需要傳入的frames是IImage的數組。

 

從中我感受到,CoreImage、CoreAnimation等圖像有關的框架非常強大,其中有很多useful的API

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM