Update
Nevermind 🙂
Figured it out using bitmapImageRepForCachingDisplayInRect & cacheDisplayInRect:toBitmapImageRep:.
I’ll leave the question here for posterity, though.
I’m working on a little application that, among other things, has an NSView subclass that draws a bunch of bezierPaths. I’d like to be able to save the drawn result as either EPS or PNG.
The view is being drawn in an offscreen window (for scaling reasons), and even though it returns the correct EPS data, I can’t seem to get any useful bitmap data from it.
EPS is no problem (I simply write the NSData from -dataWithEPSInsideRect: to a file), but I can’t seem to get a PNG bitmap.
If I try calling:
[self lockFocus];
NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:self.bounds];
[self unlockFocus];
return rep;
from a category method I’ve added to NSView, I get useless white PNG data out of it when I try representationUsingType:NSPNGFileType properties:[NSDictionary dictionary].
Strangely, if I try calling lockFocus/initBitmapWith../unlockFocus from outside the view (or its category methods), I get an exception saying that the view or one of its ancestors is hidden. And well, yes, it’s offscreen (the offscreen window’s been init’ed with defer:NO, by the way, so it should paint).
So I can either get useless data or I can get an exception. Not awesome.
To add to my confusion: If I make an NSImage containing an EPS representation, and a (useless) white bitmap, where both should be the size of the view’s bounds, the bitmap representation is always 20 pixels/units narrower than the bounds. No idea why! The EPS is the correct size.
Since this may all be related to how the offscreen window’s created, here’s the code for that (from the NSView category)
- (NSWindow*)placeInOffscreenWindow {
NSRect windowBounds = { { -1000.0 , -1000.0 } , self.bounds.size };
NSWindow *hiddenWindow = [[NSWindow alloc] initWithContentRect: windowBounds
styleMask: NSTitledWindowMask | NSClosableWindowMask
backing: NSBackingStoreNonretained
defer: NO];
[[hiddenWindow contentView] addSubview:self];
return hiddenWindow;
}
Any ideas would be appreciated!
Ended up using
bitmapImageRepForCachingDisplayInRect:&cacheDisplayInRect:toBitmapImageRep:instead