Skip to content

Instantly share code, notes, and snippets.

@aksswami
Created January 20, 2019 14:37
Show Gist options
  • Save aksswami/53bd2300d72730e32e6a76c27a0dadec to your computer and use it in GitHub Desktop.
Save aksswami/53bd2300d72730e32e6a76c27a0dadec to your computer and use it in GitHub Desktop.
Convert UIImage Array to GIF Swift
import UIKit
import CoreServices
extension UIImage {
static func createGIF(with images: [UIImage], loopCount: Int = 0, frameDelay: Double) -> Data? {
let fileProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: loopCount]] as CFDictionary
let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: frameDelay]] as CFDictionary
let cgImages = images.compactMap { $0.cgImage }
let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("animated.gif")
if let destination = CGImageDestinationCreateWithURL(url as CFURL, kUTTypeGIF, cgImages.count, nil) {
CGImageDestinationSetProperties(destination, fileProperties)
for i in 0..<images.count {
CGImageDestinationAddImage(destination, cgImages[i], frameProperties)
}
if CGImageDestinationFinalize(destination) {
return try? Data(contentsOf: url)
} else {
return nil
}
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment