Refactor image source helpers

This commit is contained in:
Reda Lemeden 2014-12-13 11:35:00 +01:00
parent 8013faea87
commit 2951bb60a1
1 changed files with 45 additions and 25 deletions

View File

@ -2,33 +2,53 @@ import UIKit
import ImageIO import ImageIO
import MobileCoreServices import MobileCoreServices
private func CGImageSourceContainsAnimatedGIF(imageSource: CGImageSource) -> Bool { internal typealias GIFProperties = [String : Double]
let isTypeGIF = UTTypeConformsTo(CGImageSourceGetType(imageSource), kUTTypeGIF) private let defaultDuration: Double = 0
let imageCount = CGImageSourceGetCount(imageSource)
return isTypeGIF != 0 && imageCount > 1
}
func CGImageSourceGIFFrameDuration(imageSource: CGImageSource, index: Int) -> NSTimeInterval { func CGImageSourceGIFFrameDuration(imageSource: CGImageSource, index: Int) -> NSTimeInterval {
let containsAnimatedGIF = CGImageSourceContainsAnimatedGIF(imageSource) if !imageSource.isAnimatedGIF { return 0.0 }
if !containsAnimatedGIF { return 0.0 }
var duration = 0.0 let duration = imageSource.GIFPropertiesAtIndex(UInt(index))
let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, UInt(index), nil) as NSDictionary >>- durationFromGIFProperties
let GIFProperties: NSDictionary? = imageProperties.objectForKey(kCGImagePropertyGIFDictionary) as? NSDictionary >>- capDuration
if let properties = GIFProperties { return duration ?? defaultDuration
duration = properties.valueForKey(kCGImagePropertyGIFUnclampedDelayTime) as Double }
if duration <= 0 { private func capDuration(duration: Double) -> Double? {
duration = properties.valueForKey(kCGImagePropertyGIFDelayTime) as Double if duration < 0 { return .None }
} let threshold = 0.02 - Double(FLT_EPSILON)
} let cappedDuration = duration < threshold ? 0.1 : duration
return cappedDuration
let threshold = 0.02 - Double(FLT_EPSILON) }
if duration > 0 && duration < threshold { private func durationFromGIFProperties(properties: GIFProperties) -> Double? {
duration = 0.1 let unclampedDelayTime = properties[String(kCGImagePropertyGIFUnclampedDelayTime)]
} let delayTime = properties[String(kCGImagePropertyGIFDelayTime)]
return duration return duration <^> unclampedDelayTime <*> delayTime
}
private func duration(unclampedDelayTime: Double)(delayTime: Double) -> Double {
let delayArray = [unclampedDelayTime, delayTime]
return delayArray.filter(isPositive).first ?? defaultDuration
}
private func isPositive(value: Double) -> Bool {
return value >= 0
}
extension CGImageSourceRef {
var isAnimatedGIF: Bool {
let isTypeGIF = UTTypeConformsTo(CGImageSourceGetType(self), kUTTypeGIF)
let imageCount = CGImageSourceGetCount(self)
return isTypeGIF != 0 && imageCount > 1
}
func GIFPropertiesAtIndex(index: UInt) -> GIFProperties? {
if !isAnimatedGIF { return .None }
let imageProperties = CGImageSourceCopyPropertiesAtIndex(self, index, nil) as Dictionary
return imageProperties[String(kCGImagePropertyGIFDictionary)] as? GIFProperties
}
} }