Skip to content

Instantly share code, notes, and snippets.

@darcwader
Created December 9, 2015 06:33
Show Gist options
  • Save darcwader/07873c811f827ef23c58 to your computer and use it in GitHub Desktop.
Save darcwader/07873c811f827ef23c58 to your computer and use it in GitHub Desktop.
Create GIF from UIImages in Swift
import CoreGraphics
import ImageIO
import MobileCoreServices
func createGIF(with images: [UIImage], loopCount: Int = 0, frameDelay: Double, callback: (dataURL: NSURL?, 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")
let destination = CGImageDestinationCreateWithURL(url, kUTTypeGIF, Int(images.count), nil)
CGImageDestinationSetProperties(destination!, fileProperties)
for i in 0..<images.count {
CGImageDestinationAddImage(destination!, images[i].CGImage!, frameProperties)
}
if CGImageDestinationFinalize(destination!) {
callback(dataURL: url, error: nil)
} else {
callback(dataURL: nil, error: NSError(domain: "createGIF", code: 0, userInfo: nil))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment