Gifu/Source/ImageSourceHelpers.swift

56 lines
1.7 KiB
Swift
Raw Normal View History

2014-09-06 14:12:09 +00:00
import UIKit
import ImageIO
import MobileCoreServices
2015-01-20 19:44:15 +00:00
import Runes
2014-09-06 14:12:09 +00:00
2014-12-13 10:35:00 +00:00
internal typealias GIFProperties = [String : Double]
private let defaultDuration: Double = 0
2014-09-06 14:12:09 +00:00
func CGImageSourceGIFFrameDuration(imageSource: CGImageSource, index: Int) -> NSTimeInterval {
2014-12-13 10:35:00 +00:00
if !imageSource.isAnimatedGIF { return 0.0 }
2014-09-06 14:12:09 +00:00
2014-12-13 10:35:00 +00:00
let duration = imageSource.GIFPropertiesAtIndex(UInt(index))
>>- durationFromGIFProperties
>>- capDuration
2014-09-06 14:12:09 +00:00
2014-12-13 10:35:00 +00:00
return duration ?? defaultDuration
}
2014-09-06 14:12:09 +00:00
2014-12-13 10:35:00 +00:00
private func capDuration(duration: Double) -> Double? {
if duration < 0 { return .None }
2014-09-06 14:12:09 +00:00
let threshold = 0.02 - Double(FLT_EPSILON)
2014-12-13 10:35:00 +00:00
let cappedDuration = duration < threshold ? 0.1 : duration
return cappedDuration
}
private func durationFromGIFProperties(properties: GIFProperties) -> Double? {
let unclampedDelayTime = properties[String(kCGImagePropertyGIFUnclampedDelayTime)]
let delayTime = properties[String(kCGImagePropertyGIFDelayTime)]
return duration <^> unclampedDelayTime <*> delayTime
}
private func duration(unclampedDelayTime: Double)(delayTime: Double) -> Double {
let delayArray = [unclampedDelayTime, delayTime]
return delayArray.filter(isPositive).first ?? defaultDuration
}
2014-09-06 14:12:09 +00:00
2014-12-13 10:35:00 +00:00
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
2014-09-06 14:12:09 +00:00
}
2014-12-13 10:35:00 +00:00
func GIFPropertiesAtIndex(index: UInt) -> GIFProperties? {
if !isAnimatedGIF { return .None }
let imageProperties = CGImageSourceCopyPropertiesAtIndex(self, index, nil) as Dictionary
return imageProperties[String(kCGImagePropertyGIFDictionary)] as? GIFProperties
}
2014-09-06 14:12:09 +00:00
}