1
1

More than 1 year has passed since last update.

【SwiftUI】ViewのスナップショットをUIImageで保存する

Last updated at Posted at 2022-05-30

元ネタはここです。

SwiftUI exporting the content of Canvas

まず、View に extension を作ります。

extension View {
    func snapshot() -> UIImage {
        let controller = UIHostingController(rootView: self)
        let view = controller.view
        
        let targetSize = controller.view.intrinsicContentSize
        view?.bounds = CGRect(origin: .zero, size: targetSize)
        view?.backgroundColor = .clear
        
        let renderer = UIGraphicsImageRenderer(size: targetSize)
        
        return renderer.image { _ in
            view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
        }
    }
}

使用例

@State var anyView = AnyView()

Button(action: {
    let image = anyView.snapshot()
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}, label: {
    Text("Get Snapshot")
})

カメラロールに画像を保存するには Info.plist に "Privacy - Photo Library Additions Usage Description" を設定する必要があります。

1
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
1
1