1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swift:あるNSWindowより下層領域のスクリーンショットを取得

Posted at

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)
    }

}
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?