Life as Clay

Archive for December 2010

From linear algebra to classic fantasy

leave a comment »

Two interesting epic journeys that I’ve come across this week:

1. A giant, comprehensive, free textbook on linear algebra.
2. Northern Journey, a truly epic classical fantasy role playing campaign. 500+ pages of back story and over 1000 pages total.

Written by Clay

December 22, 2010 at 10:12

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