Last active
November 2, 2023 13:51
-
-
Save Vinzius/3196230a2902d4ad9d0d3a55d89befe1 to your computer and use it in GitHub Desktop.
Snapshot SwiftUI View: remove strange padding on iOS 15
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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