Search code examples
objective-ccocoansimage

Adorning screenshots with NSStrings inside an NSImage


I'm trying to grab a screenshot from a NSView, draw a string on top of the screenshot using the NSImage buffer then saving everything. The view grabbed from is a plain NSPanel contentview that hosts a single NSImageView.

Unfortunately the output file is my string on an all black background with no sign of the screenshot.

This is the code:

NSImage *screenshot = [[NSImage alloc] initWithData:[mView dataWithPDFInsideRect:[mView bounds]]];

NSString *frameCounterString = @"123";
[screenshot lockFocus];
[frameCounterString drawAtPoint:NSMakePoint(10, 10) withAttributes:nil];
[screenshot unlockFocus];

Any ideas what's going on?

Writing the image directly, i.e. no string drawing yields the expected result (= screenshot in file).

As soon as the lockFocus/unlockFocus calls are added in the result goes black..

Using the NSBitmapImageRep:initWithFocusedViewRect: technique for capturing doesn't work either in this case, i.e.:

  screenshot = [[NSImage alloc] initWithSize:[mView bounds].size];
  [mView lockFocus];
  NSBitmapImageRep *bits = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[mView bounds]];
  [mView unlockFocus];
  [screenshot addRepresentation:bits];

Solution

  • Right - now compositing several NSImages as suggested by the Apple docs. One for the screenshot, than drawing that plus the string into a new empty NSImage.

    Still black.

    The view to be captured contains a NSImageView and it must be something about its internal image representations: setting the NSImageView border to none doesn't yield any screenshot, ever. Setting the border to 'Photo' allows it to be captured using the dataWithPDFInsideRect method.

    Need to find a more generic way to capture it no matter what the display mode is..