CGDisplayCreateImage 只需要壁纸屏幕截图

CGDisplayCreateImage takes only wallpapers screenshot

我想截取 Mac OS X,但我得到的只是壁纸图片。

我错过了什么?我正在使用 Mac-Catalina。

var displayCount: UInt32 = 0;
var result = CGGetActiveDisplayList(0, nil, &displayCount)
if (result != CGError.success) {
    print("error: \(result)")
    return
}
let allocated = Int(displayCount)
let activeDisplays = UnsafeMutablePointer<CGDirectDisplayID>.allocate(capacity: allocated)
result = CGGetActiveDisplayList(displayCount, activeDisplays, &displayCount)

if (result != CGError.success) {
    print("error: \(result)")
    return
}
   
for i in 1...displayCount {
    let unixTimestamp = CreateTimeStamp()
    let fileUrl = URL(fileURLWithPath: folderName + "\(unixTimestamp)" + "_" + "\(i)" + ".jpg", isDirectory: true)
    let screenShot:CGImage = CGDisplayCreateImage(activeDisplays[Int(i-1)])!
    let bitmapRep = NSBitmapImageRep(cgImage: screenShot)
    let jpegData = bitmapRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
    
    let fileManager = FileManager.default
    
   
    do {

        let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
        let fileURL = documentDirectory.appendingPathComponent("\(unixTimestamp)" + "_" + "\(i)" + ".jpg")
       
            try jpegData.write(to: fileURL)
            
       
    } catch {
       print(error)
    }

您使用外部进程截屏/usr/sbin/screencapture

只需提供-r参数即可。启动外部进程是一项非常昂贵的操作,也许有办法做到这一点 w/o 启动进程。

/usr/sbin/screencapture -r "1.png"(只需删除“-i”)

Check Screen Capture SDK