Reputation: 434
I currently have a function that creates a screenshot of the entire window in a Mac application. However, I would like to target a particular view. I know in iOS you can do the following:
extension WKWebView {
var screenshot: UIImage {
if #available(iOS 10.0, *) {
return UIGraphicsImageRenderer(size: bounds.size).image { _ in
drawHierarchy(in: CGRect(origin: .zero, size: bounds.size), afterScreenUpdates: true)
}
} else {
UIGraphicsBeginImageContext(bounds.size)
drawHierarchy(in: bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()!
return image
}
}
}
How would I convert this to Mac OS using AppKit instead of UIKit. The following is my current computed property for screenshots of the entire window.
extension WKWebView {
var screenshot: NSImage {
let displayID = CGWindowID() // cgmaindisplayid
let imageRef = CGDisplayCreateImage(displayID)
return NSImage(cgImage: imageRef!, size: (NSScreen.main?.frame.size)!)
}
}
Upvotes: 2
Views: 1603
Reputation: 236260
You can use NSView
method func dataWithPDF(inside rect: NSRect) -> Data
extension NSView {
var image: NSImage? {
return NSImage(data: dataWithPDF(inside: bounds))
}
}
Upvotes: 3