Life as Clay

How to copy contents of an NSView to the pasteboard as a .png

leave a comment »

This drove me crazy for hours, so maybe it will help somebody else.

As I explained before, I like to make things related to population pyramids. I’m still learning Cocoa, so I created this small app to generate population pyramids. It looks like this:

Population Pyramid Generator

One of the features that I wanted to implement is a menu item that reads “Copy pyramid as a .png.” I thought it would be useful for pasting it into other applications that don’t accept .pdf pasting.

This baffled me for a long time. The application is very simple… The PopPyr class is a subclass of NSView that is drawn on the window shown above. There is a PopPyrController class that binds the PopPyr instantiated in Interface Builder to the model through an IBOutlet instance called thePyramid.

To solve the problem, in the end, I wrote an IBAction method that I put into the controller called copyAsPNG:. Here’s the code:

-(IBAction)copyAsPNG:(id)sender {

	NSPasteboard *pb = [NSPasteboard generalPasteboard];
	NSBitmapImageRep *rep;

	// Telling the pasteboard what type of data we're going to send in
	[pb declareTypes:[NSArray arrayWithObjects:NSPasteboardTypePNG,nil] owner:self];

	// Creating a representation of the image within the bounds of the pyramid
	rep = [thePyramid bitmapImageRepForCachingDisplayInRect:[thePyramid bounds]];
	[thePyramid cacheDisplayInRect:[thePyramid bounds] toBitmapImageRep:rep];

	// Converting the representation to PNG and sending it to the pasteboard (with type indicated)
	[pb setData:[rep representationUsingType:NSPNGFileType properties:nil] forType:NSPasteboardTypePNG];


Thankfully, that worked. Basically, you have to create a bitmap representation of the NSView (PopPyr) and then convert it to NSData that you can send to the NSPasteboard method setData:forType:.

It’s far easier to set up copy as PDF…

-(IBAction)copyAsPDF:(id)sender {

	NSPasteboard *pb = [NSPasteboard generalPasteboard];
	[pb declareTypes:[NSArray arrayWithObjects:NSPasteboardTypePDF,nil] owner:self];
	[thePyramid writePDFInsideRect:[thePyramid visibleRect] toPasteboard:pb];

Good luck with your pasteboard methods!


Written by Clay

December 16, 2010 at 15:31

Posted in Cocoa, Code, Objective-C

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: