はじめに
今回は特定の View を UIImage に変換してフォトライブラリーに保存できるようにします
実装
プロパティを追加
UIView から image を取得するための ExtensionProperty を追加します。
extension UIView {
var image: UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0)
let context: CGContext = UIGraphicsGetCurrentContext()!
layer.render(in: context)
let capturedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return capturedImage
}
}
画像をフォトライブリーに保存する
毎度おなじみの UIImageWriteToSavedPhotosAlbum()
で画像が保存できていれば完了です。
func saveImage() {
let image = view.image
UIImageWriteToSavedPhotosAlbum(image, self, nil, nil)
}