【问题标题】:Programmatically Screenshot | Swift 3, macOS以编程方式截图 |斯威夫特 3,macOS
【发布时间】:2016-09-25 19:44:43
【问题描述】:

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

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

【问题讨论】:

  • 出于安全和隐私原因,从开发人员和用户的角度来看,它都非常重要。
  • 是的,我理解,但我无意发布这个软件,它只是用于学习和内部开发目的,如果出现一个小的“接受屏幕截图”窗口我会很好。
  • NSTask - screencapture
  • @vadian 你能指出我的示例代码或文档或其他有关“NSTask - 屏幕截图”的有用来源
  • NSTask 是运行命令行界面的 Cocoa 类 - screencapture 是制作屏幕截图的命令行界面

标签: swift macos screenshot


【解决方案1】:

是的,这是可能的。此函数获取所有连接的监视器屏幕截图并以 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)
}

【讨论】:

  • 我还没有检查你的代码,但它看起来像质量,不像我使用脚本和终端解决它的方式。没想到这么久会有答案。
  • 它有效,它是一个非常好的实现,可以处理多个显示。
  • @B.Tekkan @Magrafear 我收到一个错误 CreateTimeStamp(): let unixTimestamp = CreateTimeStamp() "use of unresolved identifier 'CreateTimeSpan'"
  • 只需为 CreateTimeStamp() 创建一个函数,该函数将 Date() 或 NSDate() 作为您需要的格式的字符串返回。
  • CreateTimeStamp() 方法只是为文件创建一个唯一的名称。我给你加了方法。
【解决方案2】:
let displayID = CGMainDisplayID()
let imageRef = CGDisplayCreateImage(displayID)

【讨论】:

    猜你喜欢
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    相关资源
    最近更新 更多