Created
January 20, 2019 14:37
-
-
Save aksswami/53bd2300d72730e32e6a76c27a0dadec to your computer and use it in GitHub Desktop.
Convert UIImage Array to GIF Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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