获取NSView的"屏幕截图"可以通过以下几种方式:
draw(_ dirtyRect:)
方法来绘制整个屏幕的截图。class MyView: NSView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
let cgContext = NSGraphicsContext.current!.cgContext
let screenSize = CGSize(width: Int(CGDisplayPixelsWide(CGMainDisplayID())), height: Int(CGDisplayPixelsHigh(CGMainDisplayID())))
// 设置CGContext的参数
cgContext.setFillColorSpace(NSColorSpace.displayP3)
cgContext.setRenderingIntent(NSColorRenderingIntent.absoluteColorRendering)
// 设置要截取的颜色(可以使用任何颜色)
let color = NSColor.black
// 截取屏幕
cgContext.fillScreen(from: NSRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height))
// 绘制要截取的颜色
color.set()
cgContext.drawRect(NSRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height), withStroke)
// 保存截图到指定路径
let screenshotURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("screenshot.png")
if let imageData = cgContext.makeImage() {
try? imageData.write(to: screenshotURL)
}
}
}class MyView: NSView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
let htmlString = "<html><body><h1>Hello, World!</h1></body></html>"
let soup = SwiftSoup.parse(htmlString)
if let element = soup.element("h1") {
element.draw(in: NSRect(x: 10, y: 10, width: 200, height: 30))
}
let screenshotURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("screenshot.png")
if let imageData = soup.render(as: NSImage.self, from: NSRect(x: 0, y: 0, width: 200, height: 30)) {
try? imageData.write(to: screenshotURL
领取专属 10元无门槛券
手把手带您无忧上云