retina画質に対応したものが取得できる。
NSImageの幅高さとCGImageの幅高さは異なることがあるので注意。
下準備
NSScreenとCGImageのExtensionを用意
import AppKit
import CoreGraphics
extension NSScreen {
var displayID: CGDirectDisplayID {
let key = NSDeviceDescriptionKey(rawValue: "NSScreenNumber")
return deviceDescription[key] as! CGDirectDisplayID
}
}
extension CGImage {
static func background(_ displayID: CGDirectDisplayID,
_ windowID: CGWindowID,
_ frame: CGRect) -> CGImage? {
let bounds = CGDisplayBounds(displayID)
let windowOptions: CGWindowListOption = [
.optionOnScreenOnly,
.optionOnScreenBelowWindow
]
let imageOptions: CGWindowImageOption = [
.bestResolution,
.boundsIgnoreFraming
]
return CGWindowListCreateImage(bounds, windowOptions, windowID, imageOptions)
}
}
画像を取得
class CustomWindow: NSWindow {
func getScreenShotUnderThisWindow() -> NSImage? {
let windowID = CGWindowID(windowNumber)
guard let screen = self.screen,
let cgImage = CGImage.background(screen.displayID, windowID, frame)
else { return nil }
return NSImage(cgImage: cgImage, size: frame.size)
}
}