0
votes

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

2 Answers

0
votes

I'm not sure why that wouldn't work (you may want to file a bug), but what I'd suggest doing instead is this:

  1. Create a new NSImage of the desired size.
  2. Lock focus on it.
  3. Tell the view to display.
  4. Draw the string.
  5. Unlock focus.
0
votes

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..