以编程方式截图| Swift 3,macOS

时间:2016-09-25 19:44:43

标签: swift macos screenshot

是否可以使用Swift 3以编程方式在mac上截取桌面? 我找不到关于这个主题的单个帖子或论坛帖子,甚至在苹果的官方文档中都没有。

到目前为止我找到了这个但似乎没有帮助:one two

2 个答案:

答案 0 :(得分:21)

是的,可能。此函数将所有连接的监视器屏幕截图和写入指定路径作为jpg文件。生成文件名为unix时间戳。

 func TakeScreensShots(folderName: String){

    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: NSBitmapImageFileType.JPEG, properties: [:])!


        do {
            try jpegData.write(to: fileUrl, options: .atomic)
        }
        catch {print("error: \(error)")}
    }
}

func CreateTimeStamp() -> Int32
{
    return Int32(Date().timeIntervalSince1970)
}

答案 1 :(得分:8)

let displayID = CGMainDisplayID()
let imageRef = CGDisplayCreateImage(displayID)