swift - 以编程方式截屏 | swift 3,macOS

标签 swift macos screenshot

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

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

最佳答案

是的,这是可能的。此功能获取所有连接的显示器屏幕截图并写入指定路径作为 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: NSBitmapImageRep.FileType.jpeg, properties: [:])!
        
        
        do {
            try jpegData.write(to: fileUrl, options: .atomic)
        }
        catch {print("error: \(error)")}
    }
}

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

关于swift - 以编程方式截屏 | swift 3,macOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39691106/

相关文章:

json - 如何在 Swift 中将 JSON 响应转换为字典格式

c# - 如何截取WPF控件的屏幕截图?

ios - CVCalendar 空白但没有错误

postgresql - brew uninstall OSX 后完全删除 postgres

windows - 如何将 Linux wxWidgets 应用程序移植到 Windows + Mac

c++ - 在 OSX 上的共享库中定义 main

android - 在React Native中处理OnePlustreeT的三指截屏

r - 将图像从剪贴板复制到 Markdown 报告

ios - 选择一个角色 - Swift/SpriteKit

ios - 使用按钮将文本添加到 UITableViewcell 中包含的文本字段值