问题
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:
- Create a new NSImage of the desired size.
- Lock focus on it.
- Tell the view to
display
. - Draw the string.
- 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