LoginSignup
7
7

More than 5 years have passed since last update.

UIView の画面キャプチャを png で保存する

Posted at

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")
        }
    }
7
7
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
7
7