Skip to content

Instantly share code, notes, and snippets.

@palmin
Created October 26, 2021 09:37
Show Gist options
  • Save palmin/408c2582bc69af0cf7397b5e42fb7f7c to your computer and use it in GitHub Desktop.
Save palmin/408c2582bc69af0cf7397b5e42fb7f7c to your computer and use it in GitHub Desktop.
extension Array where Element == UIImage {
func gifData(frameDelay: TimeInterval = 0.2) -> Data? {
let data = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(data, kUTTypeGIF, self.count, nil) else {
return nil
}
let frameProperties: CFDictionary = [kCGImagePropertyGIFDictionary as String: [(kCGImagePropertyGIFDelayTime as String): frameDelay]] as CFDictionary
let fileProperties: CFDictionary = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: 0]] as CFDictionary
CGImageDestinationSetProperties(destination, fileProperties)
for image in self {
if let cgImage = image.cgImage {
CGImageDestinationAddImage(destination, cgImage, frameProperties)
}
}
if !CGImageDestinationFinalize(destination) {
return nil
}
return data as Data
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment