Просмотр исходного кода

Merge pull request #383 from MichaelTzach/master

Fix gif frame duration calculation to match that of webkit
Wei Wang 9 лет назад
Родитель
Сommit
5a8bf00bdd
2 измененных файлов с 17 добавлено и 5 удалено
  1. 16 4
      Sources/Image.swift
  2. 1 1
      Tests/KingfisherTests/ImageCacheTests.swift

+ 16 - 4
Sources/Image.swift

@@ -232,7 +232,20 @@ extension Image {
     static func kf_animatedImageWithGIFData(gifData data: NSData, scale: CGFloat, duration: NSTimeInterval, preloadAll: Bool) -> Image? {
         
         func decodeFromSource(imageSource: CGImageSource, options: NSDictionary) -> ([Image], NSTimeInterval)? {
-
+            
+            //Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary
+            func frameDuration(fromGifInfo gifInfo: NSDictionary) -> Double {
+                let gifDefaultFrameDuration = 0.100
+                
+                let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
+                let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
+                let duration = unclampedDelayTime ?? delayTime
+                
+                guard let frameDuration = duration else { return gifDefaultFrameDuration }
+                
+                return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration
+            }
+            
             let frameCount = CGImageSourceGetCount(imageSource)
             var images = [Image]()
             var gifDuration = 0.0
@@ -248,12 +261,11 @@ extension Image {
                 } else {
                     // Animated GIF
                     guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil),
-                        gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
-                        frameDuration = (gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber) else
+                        gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary else
                     {
                         return nil
                     }
-                    gifDuration += frameDuration.doubleValue
+                    gifDuration += frameDuration(fromGifInfo: gifInfo)
                 }
                 
                 images.append(Image.kf_imageWithCGImage(imageRef, scale: scale, refImage: nil))

+ 1 - 1
Tests/KingfisherTests/ImageCacheTests.swift

@@ -238,7 +238,7 @@ class ImageCacheTests: XCTestCase {
             expectation.fulfill()
         }
         
-        self.waitForExpectationsWithTimeout(20, handler: nil)
+        self.waitForExpectationsWithTimeout(30, handler: nil)
     }
     
     func testCleanDiskCacheNotification() {