Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Snapshot SwiftUI View: remove strange padding on iOS 15
//
// View+Snapshot.swift
//
// Created by Vinzius on 2021-11-06.
//
import SwiftUI
import UIKit.UIImage
import UIKit.UIGraphicsImageRenderer
extension View {
func snapshot() -> UIImage? {
// Note: since iOS 15 it seems these two modifiers are required.
let controller = UIHostingController(
rootView: self.ignoresSafeArea()
.fixedSize(horizontal: true, vertical: true)
)
guard let view = controller.view else { return nil }
let targetSize = view.intrinsicContentSize
if targetSize.width <= 0 || targetSize.height <= 0 { return nil }
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)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment