I want to use AVCaptureScreenInput to capture a part of the screen in a SwiftUI App. Specifically, I want to only capture the area defined by a View in my app. I tried reading the view position with GeometryReader and translate that frame to screen coordinates using NSWindow.convertToScreen(_) then set AVCaptureScreenInput.cropRect to that CGRect but the captured area is always wrong. What's the correct way to get the cropRect that matches a SwiftUI view?
struct RecorderView: View {
let window: NSWindow
let input: AVCaptureScreenInput
var body: some View {
GeometryReader { geometry -> AnyView in
let previewFrame = geometry.frame(in: .global)
let screenFrame = self.window.convertToScreen(previewFrame)
self.input.cropRect = screenFrame
return AnyView(Spacer().frame(width: 200, height: 200, alignment: .center))
}
}
}
