2010-07-14 84 views
9

我需要把NSView的内容放在NSImage的实验项目中。这可能吗?我做了一些谷歌搜索,尝试了两种方法,我发现 - 但他们没有真正的工作。有什么建议么?如何拍摄NSView的“截图”?

+4

哪些方法没不工作,为什么? – 2010-07-14 23:20:35

回答

19
[[NSImage alloc] initWithData:[view dataWithPDFInsideRect:[view bounds]]]; 
+0

非常感谢。 – Debashis 2010-07-15 02:11:53

+2

+1值得注意的是,尽管这是一般的正确方法,但有些情况下它不起作用,例如像'NSOpenGLView'这样的视图有自己的OpenGL渲染上下文。在这种情况下,您需要直接获取像素数据,并从中创建一个位图代表,这不太整洁。 – walkytalky 2010-07-19 01:11:06

+0

Obs:阴影和cornerRadius将被忽略 – codrut 2017-09-25 08:30:45

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

从WWDC 2012届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) 
+0

swift 3 let rep = viewToCapture.bitmapImageRepForCachingDisplay(in:viewToCapture.bounds)! viewToCapture.cacheDisplay(在:viewToCapture.bounds,至:REP) 让IMG = NSImage中(尺寸:viewToCapture.bounds.size) img.addRepresentation(REP) – spacecash21 2017-07-02 17:56:43

+0

注:不总是正常工作。我已经发布了带有旋转坐标系的标签。 – Ash 2017-07-04 14:16:30

+0

这对我来说是最好的解决方案,与pdf版本不同,这也是阴影和圆角的原因。与窗口版本不同,这只能捕捉当前视图。 Obj C code: ' - (NSImage *)screenCap { \t NSBitmapImageRep * bitmap = [self bitmapImageRepForCachingDisplayInRect:self.bounds]; \t [self cacheDisplayInRect:self.bounds toBitmapImageRep:bitmap]; \t NSImage * result = [[NSImage alloc] initWithSize:self.bounds.size]; \t [result addRepresentation:bitmap]; \t返回结果; } ' – codrut 2017-10-16 13:36:27