I know that you can turn an IOS SwiftUI view into an image by following these steps, but this uses UIKit things in the SwiftUI extension which you cannot use in macOS SwiftUI. Does anyone know how to snapshot/screenshot a macOS SwiftUI View?
1 Answer
In macOS same approach can be used. NSHostingController
is analog of UIHostingController
. Also to get it drawn the view should be added to some window:
extension View {
func snapshot() -> NSImage? {
let controller = NSHostingController(rootView: self)
let targetSize = controller.view.intrinsicContentSize
let contentRect = NSRect(origin: .zero, size: targetSize)
let window = NSWindow(
contentRect: contentRect,
styleMask: [.borderless],
backing: .buffered,
defer: false
)
window.contentView = controller.view
guard
let bitmapRep = controller.view.bitmapImageRepForCachingDisplay(in: contentRect)
else { return nil }
controller.view.cacheDisplay(in: contentRect, to: bitmapRep)
let image = NSImage(size: bitmapRep.size)
image.addRepresentation(bitmapRep)
return image
}
}
-
Thank you so much! I've tried so many different code snippets to try to get this to work but this one finally did something. However, I needed to put everything from
controller.view.cacheDisplay
onward into aDispatchQueue.main.async
block and return the result in a completion handler. I also hardcoded the targetSize for now because my view wasn't returning the rightintrinsicContentSize
, but that's an unrelated issue.– AngelaNov 4, 2022 at 21:31 -
Okay, it turns out if you set the size of the view explicitly with
.frame(...)
, then not only doesintrinsicContentSize
work, but you can also callwindow.contentView?.layout()
(without it crashing for lack of defined size) to make it work without usingDispatchQueue.main.async
.– AngelaNov 7, 2022 at 22:15