是的,这是可能的。这个函数会拍摄所有连接的显示器截图,并将其作为 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)
}
let unixTimestamp = CreateTimeStamp()
"use of unresolved identifier 'CreateTimeSpan'" - user6879072let displayID = CGMainDisplayID()
let imageRef = CGDisplayCreateImage(displayID)
NSTask
是 Cocoa 类,用于运行命令行接口。screencapture
是用于截屏的命令行接口。 - vadian