简体   繁体   中英

Drawing text onto an NSImage in a loop - but how do I clear the cache?

I have an NSTimer calling a method once a second, which checks a simple integer value, called 'total'. This value is then drawn on top of an NSImage and displayed on the screen.

NSImage *totalIcon = [NSImage imageNamed:@"round_red"];
[totalIcon lockFocus];
NSString *totalString = [NSString stringWithFormat:@"%d", total];
[totalString drawAtPoint:NSZeroPoint withAttributes:nil];
[totalIcon unlockFocus];

My expectation was that on every iteration, totalIcon would start afresh and take on the original round_red image. But it actually appears to be doing some caching. So I checked the NSImage reference and saw that I could do this:

[totalIcon setCacheMode:NSImageCacheNever];

But this seems to have no effect because on every new iteration, totalIcon's value is set to a modified round_red, which includes the previous values written on it. I wanted to start with a clean image each time.

What am I doing wrong? Is it being cached somewhere else? If anyone is kind enough to help, I would value answers that are simple over the most efficient, as I would like to understand my code and will optimize it later, if required.

Use initWithContentsOfFile: to create your image instead of imageNamed:. That method does not cause the image to be cached.

NSImage *totalIcon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"round_red" ofType:@"jpg"]]; // change @"jpg" to whatever is appropriate for your image file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM