[swift] scenekit / Screenshotを取得してライブラリに保存する方法

scenekit / Screenshotを取得してライブラリに保存する方法は以下の通り

scenekitでは通常通りのScreenshotの取得方法でレンダリングされたシーンが取得できないため、SceneViewで用意されているsnapshot()を使用する

前準備として、info.plistに「Privacy – Photo Library Usage Description」に使用理由を記述しておくこと

infoplist_camera

 

import UIKit
import SceneKit

class GameViewController: UIViewController {

    @IBOutlet var scnView: SCNView!

    override func viewDidLoad() {
        super.viewDidLoad()
        //シーンの前準備は省略
    }

// セーブを行う
    @IBAction func saveImage() {
        
        let targetImage = scnView.snapshot() as UIImage
        
        // UIImage の画像をカメラロールに画像を保存
        UIImageWriteToSavedPhotosAlbum(targetImage, self, #selector(self.showResultOfSaveImage(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    // 保存を試みた結果をダイアログで表示
    @objc func showResultOfSaveImage(_ image: UIImage, didFinishSavingWithError error: NSError!, contextInfo: UnsafeMutableRawPointer) {
        
        var title = "Completed"
        var message = "Completed to save on Liblary"
        
        if error != nil {
            title = "Error"
            message = "Fail to save"
        }
        
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        // OKボタンを追加
        alert.addAction(UIAlertAction(title: "OK",
                                      style: UIAlertActionStyle.default,
                                      handler:{
                                        (action:UIAlertAction!) -> Void in
                                        print("save")
        }))
        
        // UIAlertController を表示
        self.present(alert, animated: true, completion: nil)
    }

}

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です