Paul Patterson
Paul Patterson

Reputation: 6918

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?

Upvotes: 0

Views: 687

Answers (2)

Rupert Pupkin
Rupert Pupkin

Reputation: 790

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];
}

Upvotes: 1

d00dle
d00dle

Reputation: 1316

I would suggest making a copy of the desired NSView offscreen and taking a snapshot of that.

Upvotes: 0

Related Questions