Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I take a "screenshot" of an NSView?

I need to take the contents of an NSView and put them in an NSImage, for an experimental project. Is this possible? I did some Googling, tried two methods that I found - but they didn't really work. Any suggestions?

like image 808
Debashis Avatar asked Jul 14 '10 23:07

Debashis


1 Answers

From WWDC 2012 Session 245 (translated to Swift):

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)
like image 137
Klaas Avatar answered Nov 02 '22 17:11

Klaas