问题
I have an NSSegmentedControl(todayButton) that contains an image. I'm trying to draw some text onto the image using the following:
NSImage *img = [todayButton imageForSegment:0]
[img lockFocus]
[@"15" drawAtPoint:NSZeroPoint withAttributes:nil]
[img unlockFocus]
[img setTemplate:YES]
The image gets set as a template and no errors are thrown but no text appears on the image.
回答1:
I may be entirely wrong, but my gut tells me you may be running into NSImage caching issues. The system caches images unless you change the settings for an image (usually not the best approach for an image you want to reuse) or simply create a new one versus loading one from the bundle.
You may need to make a new image from scratch, composite whatever background (what you were getting from your button segment) into it, then draw the text. Otherwise the system is caching something it got elsewhere, which can sometimes lead to undefined (or at least unexpected) behavior.
回答2:
Try calling setImage:forSegment:
after modifying the image. It is very possible that the image you're handed back is a copy.
As a side note not related to the question, setTemplate:
takes a BOOL
, not a C++ bool
. You should pass YES
, not true
. This suggests that you may be compiling view controller code as ObjC++. If so, I really recommend against that.
来源:https://stackoverflow.com/questions/13873764/cocoa-draw-text-on-nsimage