Search code examples
objective-ccapturensbox

Capture NSBox Subclass to PNG


I'm currently trying to capture the contents of my NSBox subclass to a PNG file. I've found some code that seems to do the trick perfectly (code that I call from my actual subclass):

[self lockFocus];

NSBitmapImageRep *rep = [self bitmapImageRepForCachingDisplayInRect:[self bounds]];

[self cacheDisplayInRect:[self bounds] toBitmapImageRep:rep];

[self unlockFocus];

NSData *imageData = [rep representationUsingType:NSPNGFileType properties:nil];

[imageData writeToFile:@"~/Desktop/test.png" atomically:NO];    

As I said, that code works quite well, but there's only one small issue: the NSBox is actually transparent, so the image looks very strange to the user, who's used to having the default whitish-gray background.

I haven't succesfully called this from my main, AppDelegate. That should solve the problem, capturing what's behind the NSBox as well, but it's not working for me.

Does anyone know how to capture anything behind this NSBox as well as its contents?


Solution

  • Though not super-efficient, you might try drawing the window's background manually in the NSBox subclass:

    - (void) drawRect:(NSRect)dirtyRect {
    
        NSDrawWindowBackground(dirtyRect);
        [super drawRect:dirtyRect];
    }