Last active
October 29, 2023 07:31
-
-
Save NikhilManapure/6f4c4e18692d51d6a8acfdc440dcac5f to your computer and use it in GitHub Desktop.
Create Gif from array of UIImages in Swift 3
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 Foundation | |
import UIKit | |
import ImageIO | |
import MobileCoreServices | |
extension UIImage { | |
static func animatedGif(from images: [UIImage]) { | |
let fileProperties: CFDictionary = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: 0]] as CFDictionary | |
let frameProperties: CFDictionary = [kCGImagePropertyGIFDictionary as String: [(kCGImagePropertyGIFDelayTime as String): 1.0]] as CFDictionary | |
let documentsDirectoryURL: URL? = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) | |
let fileURL: URL? = documentsDirectoryURL?.appendingPathComponent("animated.gif") | |
if let url = fileURL as CFURL? { | |
if let destination = CGImageDestinationCreateWithURL(url, kUTTypeGIF, images.count, nil) { | |
CGImageDestinationSetProperties(destination, fileProperties) | |
for image in images { | |
if let cgImage = image.cgImage { | |
CGImageDestinationAddImage(destination, cgImage, frameProperties) | |
} | |
} | |
if !CGImageDestinationFinalize(destination) { | |
print("Failed to finalize the image destination") | |
} | |
print("Url = \(fileURL)") | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
it is very useful, thank you!