我想要获取屏幕图像,忽略我的应用程序窗口。
在Objective-C中找到一个代码示例,并尝试将其转换为Swift。
Objective-C剪辑:
// Get onscreen windows
CGWindowID windowIDToExcude = (CGWindowID)[myNSWindow windowNumber];
CFArrayRef onScreenWindows = CGWindowListCreate(kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
CFMutableArrayRef finalList = CFArrayCreateMutableCopy(NULL, 0, onScreenWindows);
for (long i = CFArrayGetCount(finalList) - 1; i >= 0; i--) {
CGWindowID window = (CGWindowID)(uintptr_t)CFArrayGetValueAtIndex(finalList, i);
if (window == windowIDToExcude)
CFArrayRemoveValueAtIndex(finalList, i);
}
// Get the composite image
CGImageRef ref = CGWindowListCreateImageFromArray(myRectToGrab, finalList, kCGWindowListOptionAll);
我在Swift中的版本(我设法到目前为止):
// Get onscreen windows
let windowIDToExcude = myNSWindow.windowNumber!
let onScreenWindows = CGWindowListCreate(kCGWindowListOptionOnScreenOnly, kCGNullWindowID)
let finalList = CFArrayCreateMutableCopy(nil, 0, onScreenWindows)
for var i = CFArrayGetCount(finalList) - 1; i >= 0; i-=1 {
var window: CGWindowID = (uintptr_t(CFArrayGetValueAtIndex(finalList, i)) as! CGWindowID)
if window == windowIDToExcude {
CFArrayRemoveValueAtIndex(finalList, i)
}
}
// Get the composite image
var ref = CGWindowListCreateImageFromArray(myRectToGrab, finalList, kCGWindowListOptionAll)
但它在swift 2.0中不起作用,我不知道为什么。
特别是这行不能编译:
CGWindowListCreate(kCGWindowListOptionOnScreenOnly,kCGNullWindowID)
显然不再有CGWindowListCreate
,kCGWindowListOptionOnScreenOnly
和kCGNullWindowID
这样的事情了。
答案 0 :(得分:3)
你可以试试这个:
let imageRef = CGWindowListCreateImage(self.view.frame, CGWindowListOption.OptionOnScreenBelowWindow, CGWindowID(self.view.window!.windowNumber), CGWindowImageOption.Default)
let image = NSImage(CGImage: imageRef!, size: self.view.frame.size)
self.imageView.image = image
这对我有用。