Adorning screenshots with NSStrings inside an NSImage

天涯浪子 提交于 2020-01-03 06:47:08

问题


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

回答1:


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.



回答2:


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



来源:https://stackoverflow.com/questions/8885561/adorning-screenshots-with-nsstrings-inside-an-nsimage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!