Cocoa draw text on NSImage

I have an NSSegmentedControl (TodayButton) that contains an image. I am trying to draw text on an image using the following:

NSImage *img = [todayButton imageForSegment:0] [img lockFocus] [@"15" drawAtPoint:NSZeroPoint withAttributes:nil] [img unlockFocus] [img setTemplate:YES] 

The image is set as a template, and no errors occur, but the image does not display text.

+4
source share
2 answers

I might be wrong, but my gut says that you may run into NSImage caching problems. The system caches images if you do not change the image settings (usually this is not the best approach to the image that you want to reuse) or just create a new one or download it from the package.

You may need to create a new image from scratch, create some kind of background (what you got from your button segment), then draw the text. Otherwise, the system caches something elsewhere, which sometimes leads to undefined (or at least unexpected) behavior.

0
source

Try calling setImage:forSegment: after changing the image. It is very possible that the image you received back is a copy.


As a side note not related to the question, setTemplate: takes BOOL , not C ++ BOOL . You must pass YES , not true . This suggests that you can compile the view controller code as ObjC ++. If so, I really recommend against it.

0
source

All Articles