Objective c 我该怎么取“a”呢;截图;一个新的视角?

Objective c 我该怎么取“a”呢;截图;一个新的视角?,objective-c,cocoa,macos,nsview,nsimage,Objective C,Cocoa,Macos,Nsview,Nsimage,我需要把NSView的内容放在NSImage中,作为一个实验项目。这可能吗?我在谷歌上搜索了一下,尝试了两种我发现的方法——但都不管用。有什么建议吗?我想,德巴西斯正在考虑更多类似的事情 [[NSImage alloc] initWithData:[view dataWithPDFInsideRect:[view bounds]]]; 来自WWDC 2012年第245期会议的问候语(翻译成Swift): let dataOfView = view.dataWithPDFInsideRect(v

我需要把
NSView
的内容放在
NSImage
中,作为一个实验项目。这可能吗?我在谷歌上搜索了一下,尝试了两种我发现的方法——但都不管用。有什么建议吗?

我想,德巴西斯正在考虑更多类似的事情

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

来自WWDC 2012年第245期会议的问候语(翻译成Swift):

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

哪些方法不起作用以及原因?+1值得注意的是,尽管这通常是正确的方法,但在某些情况下它不起作用,例如具有自己的OpenGL渲染上下文的视图,如
NSOpenGLView
。在这种情况下,您需要直接获取像素数据并从中创建位图代表,这有点不整洁。Obs:阴影和cornerRadius将被忽略。如果视图是层备份的(wantsLayer=YES),此解决方案将忽略一些层属性,如backgroundColor、cornerRadius等。我建议使用另一个答案中的代码,使用cacheDisplayInRect函数,它应该在所有情况下都能工作。链接现在断开,使用3 let rep=viewToCapture.bitmapImageRepForCachingDisplay(在:viewToCapture.bounds中)!viewToCapture.cacheDisplay(in:viewToCapture.bounds,to:rep)让img=NSImage(size:viewToCapture.bounds.size)img.addRepresentation(rep)注意:并不总是正常工作。我已经发布了一个带有旋转坐标系的标签。这对我来说是最好的解决方案,与pdf版本不同,它还考虑了阴影和圆角。与“窗口封口”版本不同,这仅捕获当前视图。对象C代码:
-(NSImage*)屏幕上限{NSBitmapImageRep*位图=[self-bitmapImageRepForCachingDisplayInRect:self.bounds];[self-cacheDisplayInRect:self.bounds toBitmapImageRep:bitmap];NSImage*结果=[nsImageAlloc]initWithSize:self.bounds.size];[result addRepresentation:bitmap];返回结果;}
我在10.14和10.15中成功地使用了它(上面是codrut的Obj C版本),但由于某些原因,我在10.13中没有得到任何图像。
let viewToCapture = self.window!.contentView!
let rep = viewToCapture.bitmapImageRepForCachingDisplay(in: viewToCapture.bounds)!
viewToCapture.cacheDisplay(in: viewToCapture.bounds, to: rep)

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