以编程方式截图| Swift 3,macOS [英] Programmatically Screenshot | Swift 3, macOS

查看:136
本文介绍了以编程方式截图| Swift 3,macOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用Swift 3在Mac上以编程方式拍摄桌面截图? 我找不到关于该主题的单个主题或论坛帖子,甚至在Apple的官方文档中也找不到.

Is it possible to take a screenshot programmatically of the desktop on mac using Swift 3? I can't find a single thread or forum post about the topic, not even in apple's official documentation.

到目前为止,我发现了这一点,但似乎无济于事:两个

I have found this so far but it doesn't seem to help: one two

推荐答案

是可能的.此功能获取所有连接的监视器的屏幕截图,并将其作为jpg文件写入指定的路径.生成文件名作为Unix时间戳.

Yes its possible. This function takes all connected monitors screenshots and writes to specified path as jpg file. Generates file name as unix time stamp.

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

这篇关于以编程方式截图| Swift 3,macOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆