如何获取NSView的“屏幕截图”?

时间:2010-07-14 23:11:13

标签: objective-c cocoa macos nsview nsimage

我需要获取NSView的内容并将它们放在NSImage中,用于实验项目。这可能吗?我做了一些谷歌搜索,尝试了我找到的两种方法 - 但它们并没有真正起作用。有什么建议吗?

4 个答案:

答案 0 :(得分:22)

[[NSImage alloc] initWithData:[view dataWithPDFInsideRect:[view bounds]]];

答案 1 :(得分:16)

从WWDC 2012 Session 245(翻译为Swift):

let viewToCapture = self.window!.contentView!
let rep = viewToCapture.bitmapImageRepForCachingDisplayInRect(viewToCapture.bounds)!
viewToCapture.cacheDisplayInRect(viewToCapture.bounds, toBitmapImageRep: rep)

let img = NSImage(size: viewToCapture.bounds.size)
img.addRepresentation(rep)

答案 2 :(得分:6)

let dataOfView = view.dataWithPDFInsideRect(view.bounds)
let imageOfView = NSImage(data: dataOfView)

答案 3 :(得分:3)