Search code examples
cocoansviewnsimage

Making an NSImage out of an NSView


I know how to create an NSImage depicting an NSView and all its subviews, but what I'm after is an NSImage of a view ignoring its subviews. I can think of ways of doing this with a subclass of NSView, but I'm keen to avoid subclassing if possible. Does anyone have any ideas?


Solution

  • Hide the subviews, grab the image, unhide the subviews:

    NSMutableArray* hiddenViews = [[NSMutableArray] alloc init];
    
    for (NSView* subview in [self subviews]) {
        if (subview hidden) [hiddenViews addObject: subview];
        else [subview setHidden:YES];
    }
    
    NSSize imgSize = self.bounds.size;
    NSBitmapImageRep * bir = [self bitmapImageRepForCachingDisplayInRect:[self bounds]];
    [bir setSize:imgSize];
    [self cacheDisplayInRect:[self bounds] toBitmapImageRep:bir];
    NSImage* image = [[NSImage alloc] initWithSize:imgSize];
    [image addRepresentation:bir];
    
    for (NSView* subview in [self subviews]) {
        if (![hiddenViews containsObject: subview])
            [subview setHidden:NO];
    }