Skip to content

Instantly share code, notes, and snippets.

@uruly
Created April 12, 2018 08:36
Show Gist options
  • Save uruly/a862a89c6e433f8fa52f75e4df631439 to your computer and use it in GitHub Desktop.
Save uruly/a862a89c6e433f8fa52f75e4df631439 to your computer and use it in GitHub Desktop.
import UIKit
import AVFoundation
import ImageIO
import MobileCoreServices
import WebKit
class GIFWebViewController: UIViewController {
var imageArray:[CGImage]!
//フレームレート
let frameRate = CMTimeMake(1,5)
override func viewDidLoad() {
super.viewDidLoad()
imageArray = []
//適当に入れておく
for i in 1 ..< 3 {
if let image = UIImage(named:"image\(i).png")?.cgImage {
imageArray.append(image)
}
}
makeGifImage { url in //成功した時だけ
let animationGifView = WKWebView(frame: CGRect(x:0,y:0,width:300,height:200))
animationGifView.backgroundColor = UIColor.lightGray
animationGifView.load(URLRequest(url: url))
self.view.addSubview(animationGifView)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func makeGifImage(_ completion:(URL)->()){
//ループカウント 0で無限ループ
let fileProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: 0]]
//フレームレート
let frameProperties = [kCGImagePropertyGIFDictionary as String:[kCGImagePropertyGIFDelayTime as String :CMTimeGetSeconds(frameRate)]]
let url = URL(fileURLWithPath:NSTemporaryDirectory()).appendingPathComponent("\(UUID().uuidString).gif")
guard let destination = CGImageDestinationCreateWithURL(url as CFURL,kUTTypeGIF,imageArray.count,nil)else{
print("CGImageDestinationの作成に失敗")
return
}
CGImageDestinationSetProperties(destination,fileProperties as CFDictionary?)
//画像を追加
for image in imageArray{
CGImageDestinationAddImage(destination,image,frameProperties as CFDictionary?)
}
if CGImageDestinationFinalize(destination){
//GIF生成後の処理をする
print("成功")
completion(url)
}else{
print("GIF生成に失敗")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment