0
1

More than 3 years have passed since last update.

6行で UIView を UIImage に変換してサクッと画像を保存する

Posted at

はじめに

今回は特定の 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)
    }
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1