class GifManager {private func getdocumentsDirectory() -> URL? { return fileManager.default.urls(for: .documentDirectory,in: .userDomainMask).first}public func generateGif(photos: [UIImage],filename: String) -> Bool { if let docsDirectory = getdocumentsDirectory() { let url = docsDirectory.appendingPathComponent(filename) let filePropertIEs = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: 0]] let gifPropertIEs = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: 0.125]] if let destination = CGImageDestinationCreateWithURL(url as CFURL,kUTTypeGIF,photos.count,nil) { CGImageDestinationSetPropertIEs(destination,filePropertIEs as CFDictionary?) for photo in photos { CGImageDestinationAddImage(destination,photo.cgImage!,gifPropertIEs as CFDictionary?) } return CGImageDestinationFinalize(destination) } } return false}public func saveGifToCameraRoll(filename: String) { if let docsDirectory = getdocumentsDirectory() { let fileUrl: URL = docsDirectory.appendingPathComponent(filename) do { let data = try Data(contentsOf: fileUrl) if let _ = UIImage(data: data) { PHPhotolibrary.shared().performChanges({ PHAssetChangeRequest.creationRequestForAssetFromImage(atfileURL: fileUrl) },completionHandler: {completed,error in if error != nil { print("error") } else if completed { print("completed") } else { print("not completed") } }) } } catch let error { print(error) } }}解决方法 Swift 3.1
对于那些想要更新版本的GIF生成功能的人,我已将其包含在此处.
此函数需要ImageIO和MobileCoreServices导入语句.
import ImageIOimport MobileCoreServices
这是功能.
func generateGif(photos: [UIImage],filename: String) -> Bool { let documentsDirectoryPath = NSSearchPathForDirectorIEsInDomains(.documentDirectory,.userDomainMask,true)[0] let path = documentsDirectoryPath.appending(filename) let filePropertIEs = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: 0]] let gifPropertIEs = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: 0.125]] let cfURL = URL(fileURLWithPath: path) as CFURL if let destination = CGImageDestinationCreateWithURL(cfURL,gifPropertIEs as CFDictionary?) } return CGImageDestinationFinalize(destination) } return false}
编辑:
它有一个Bool,所以你知道你可以安全地使用它创建的文件.
if generateGif(arrayOfImages,"/myGIFfile.gif") { // do something with gif} else { // Failed to create and close the gif file}总结
以上是内存溢出为你收集整理的ios – 通过Swift 3.0生成并导出GIF动画?全部内容,希望文章能够帮你解决ios – 通过Swift 3.0生成并导出GIF动画?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)