How to grab an NSImage from an NSView

January 23, 2009

Here’s one way to create an image of a view. There may be a better way, but this certainly works. If you do know of a better way, then please comment.
Self is an NSView.

NSRect boxrect = self.bounds;
NSData* pdf = [self dataWithPDFInsideRect:boxrect];
NSImage* viewSnapshot = [[NSImage alloc] initWithData:pdf];

You can then go on to make a translucent version of the image. This is useful for drag & drop.

NSImage* dragImage = [[NSImage alloc] initWithSize:viewSnapshot.size];
[dragImage lockFocus];
[viewSnapshot dissolveToPoint:NSZeroPoint fraction:0.85];
[dragImage unlockFocus];

Note that I’m using garbage collection here.  Alter as necessary if you need to manage memory.

On Apple’s site there’s a demo of how to do screenshots of windows or the whole screen.  It’s called SonOfGrab and it’s Leopard only.  I’ve not yet tried it myself.


Programmer’s Notebook

January 23, 2009

Every programmer from time to time spends hours trying to find out how to solve a problem.  And as often as not the end result is a couple of lines to call an unfamiliar API.

The intent of this blog is to log these solutions to problems in OS X when I hit them.  It will act as my personal programmer’s notebook, and also hopefully help others who arrive here from Google.

Also it seems like a good place to store links to great OS X programmers resources elsewhere.


Design a site like this with WordPress.com
Get started