<p>For part of my application I have a need to create an image of a certain view and all of its subviews.</p>

<p>To do this I'm creating a context that wraps a bitmap with the same-size as the view, but I'm unsure how to draw the view hierarchy into it. I can draw a single view just be setting the context and explicitly calling drawRect, but this does not deal with all of the subviews.</p>

<p>I can't see anything in the NSView interface that could help with this so I suspect the solution may lie at a higher level.</p>

[{'answer_id': 14947, 'author': 'Chris Hanson', 'author_id': 714, 'author_profile': 'https://Stackoverflow.com/users/714', 'pm_score': 2, 'selected': False, 'text': '<p>You can use <a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/Reference/NSView.html#//apple_ref/occ/instm/NSView/dataWithPDFInsideRect:" rel="nofollow noreferrer" title="-[NSData dataWithPDFInsideRect:]"><code>-[NSView dataWithPDFInsideRect:]</code></a> to render the entire hierarchy of the view you send it to into a PDF, returned as an <code>NSData</code> object.  You can then do whatever you wish with that, including render it into a bitmap.</p>\n\n<p>Are you sure you want a bitmap representation though?  After all, that PDF could be (at least in theory) resolution-independent.</p>\n'}, {'answer_id': 15489, 'author': 'Chris Hanson', 'author_id': 714, 'author_profile': 'https://Stackoverflow.com/users/714', 'pm_score': 1, 'selected': False, 'text': '<p>You can use <a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSBitmapImageRep_Class/Reference/Reference.html#//apple_ref/occ/instm/NSBitmapImageRep/initWithFocusedViewRect:" rel="nofollow noreferrer" title="-[NSBitmapImageRep initWithFocusedViewRect:]"><code>-[NSBitmapImageRep initWithFocusedViewRect:]</code></a> after locking focus on a view to have the view render itself (and its subviews) into the given rectangle.</p>\n'}, {'answer_id': 66556, 'author': 'charles', 'author_id': 9900, 'author_profile': 'https://Stackoverflow.com/users/9900', 'pm_score': 3, 'selected': True, 'text': "<p>I found that writing the drawing code myself was the best way to:</p>\n\n<ul>\n<li>deal with potential transparency issues (some of the other options do add a white background to the whole image)</li>\n<li>performance was much better</li>\n</ul>\n\n<p>The code below is not perfect, because it does not deal with scaling issues when going from bounds to frames, but it does take into account the isFlipped state, and works very well for what I used it for. Note that it only draws the subviews (and the subsubviews,... recursively), but getting it to also draw itself is very easy, just add a <code>[self drawRect:[self bounds]]</code> in the implementation of <code>imageWithSubviews</code>.</p>\n\n<pre><code>- (void)drawSubviews\n{\n    BOOL flipped = [self isFlipped];\n\n    for ( NSView *subview in [self subviews] ) {\n\n        // changes the coordinate system so that the local coordinates of the subview (bounds) become the coordinates of the superview (frame)\n        // the transform assumes bounds and frame have the same size, and bounds origin is (0,0)\n        // handling of 'isFlipped' also probably unreliable\n        NSAffineTransform *transform = [NSAffineTransform transform];\n        if ( flipped ) {\n            [transform translateXBy:subview.frame.origin.x yBy:NSMaxY(subview.frame)];\n            [transform scaleXBy:+1.0 yBy:-1.0];\n        } else\n            [transform translateXBy:subview.frame.origin.x yBy:subview.frame.origin.y];\n        [transform concat];\n\n        // recursively draw the subview and sub-subviews\n        [subview drawRect:[subview bounds]];\n        [subview drawSubviews];\n\n        // reset the transform to get back a clean graphic contexts for the rest of the drawing\n        [transform invert];\n        [transform concat];\n    }\n}\n\n- (NSImage *)imageWithSubviews\n{\n    NSImage *image = [[[NSImage alloc] initWithSize:[self bounds].size] autorelease];\n    [image lockFocus];\n    // it seems NSImage cannot use flipped coordinates the way NSView does (the method 'setFlipped:' does not seem to help)\n    // Use instead an NSAffineTransform\n    if ( [self isFlipped] ) {\n        NSAffineTransform *transform = [NSAffineTransform transform];\n        [transform translateXBy:0 yBy:NSMaxY(self.bounds)];\n        [transform scaleXBy:+1.0 yBy:-1.0];\n        [transform concat];\n    }\n    [self drawSubviews];\n    [image unlockFocus];\n    return image;\n}\n</code></pre>\n"}, {'answer_id': 71696, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>What you want to do is available explicitly already.  See the section "NSView Drawing Redirection API" in the 10.4 AppKit release notes.</p>\n\n<p>Make an NSBitmapImageRep for caching and clear it:</p>\n\n<pre><code>NSGraphicsContext *bitmapGraphicsContext = [NSGraphicsContext graphicsContextWithBitmapImageRep:cacheBitmapImageRep];\n[NSGraphicsContext saveGraphicsState];\n[NSGraphicsContext setCurrentContext:bitmapGraphicsContext];\n[[NSColor clearColor] set];\nNSRectFill(NSMakeRect(0, 0, [cacheBitmapImageRep size].width, [cacheBitmapImageRep size].height));\n[NSGraphicsContext restoreGraphicsState];\n</code></pre>\n\n<p>Cache to it:</p>\n\n<pre><code>-[NSView cacheDisplayInRect:toBitmapImageRep:]\n</code></pre>\n\n<p>If you want to more generally draw into a specified context handling view recursion and transparency correctly, </p>\n\n<pre><code>-[NSView displayRectIgnoringOpacity:inContext:]\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/14874', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1043/']