Skip to content

Instantly share code, notes, and snippets.

@fengdragon
Forked from westerlund/gif.swift
Created September 22, 2016 09:32
Show Gist options
  • Save fengdragon/f48d9db23aba44031edd5c688197d4da to your computer and use it in GitHub Desktop.
Save fengdragon/f48d9db23aba44031edd5c688197d4da to your computer and use it in GitHub Desktop.
Create an animated gif in swift
func createGIF(with images: [UIImage], loopCount: Int = 0, frameDelay: Double, callback: (data: NSData?, error: NSError?) -> ()) {
let fileProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: loopCount]]
let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: frameDelay]]
let documentsDirectory = NSTemporaryDirectory()
let url = NSURL(fileURLWithPath: documentsDirectory)?.URLByAppendingPathComponent("animated.gif")
if let url = url {
let destination = CGImageDestinationCreateWithURL(url, kUTTypeGIF, UInt(images.count), nil)
CGImageDestinationSetProperties(destination, fileProperties)
for i in 0..<images.count {
CGImageDestinationAddImage(destination, images[i].CGImage, frameProperties)
}
if CGImageDestinationFinalize(destination) {
callback(data: NSData(contentsOfURL: url), error: nil)
} else {
callback(data: nil, error: NSError())
}
} else {
callback(data: nil, error: NSError())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment