View の画面キャプチャをとる方法はググればいくつか出て来るが、 jpg で保存してしまうと画像が劣化してしまう。
なので取得した UIImage を png に変換してから保存すれば綺麗な画像のまま保存できる。
UIView+Ex:
import UIKit
extension UIView {
func snapshot() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
let context = UIGraphicsGetCurrentContext()!
context.setShouldAntialias(false)
layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
let png = UIImagePNGRepresentation(image)!
let pngImage = UIImage.init(data: png)!
return pngImage
}
}
ViewController:
func save() {
UIImageWriteToSavedPhotosAlbum(view.snapshot(), self, #selector(saved(_: didFinishSavingWithError: contextInfo:)), nil)
}
@objc private func saved(_ image: UIImage, didFinishSavingWithError error: NSError!, contextInfo: UnsafeMutableRawPointer) {
if error != nil {
print("error")
} else {
print("success")
}
}