Search code examples
cocoamacosnsimagehud

HUD Buttons using Template Images


I'm building a semi-transparent floating HUD window in my application, which is intended to look like the Quick Look HUD window, specifically using the Enter/Exit full screen image. Cocoa provides the NSEnterFullScreenTemplate (and NSExitFullScreenTemplate) templates, which serve this purpose, and work fine on bordered buttons.

As soon as I remove the border and put the button on a dark background though, it keeps a dark gray color, and makes it difficult to see. I'd like to make it white, like in Quick Look. Is there a built-in way to do this, or do I have to resort to scaling and coloring the image myself?


Solution

  • I ended up writing an NSImage category class method that returns a template image at the desired size and in the desired color (basically doing it myself, as I don't think the API does provide a way to do this).

    +(NSImage *)templateImage:(NSString *)templateName
                    withColor:(NSColor *)tint
                      andSize:(CGSize)targetSize
    {
        NSImage *template = [NSImage imageNamed:templateName];
        NSSize size = (CGSizeEqualToSize(targetSize, CGSizeZero)
                       ? [template size]
                       : targetSize);
        NSRect imageBounds = NSMakeRect(0, 0, size.width, size.height);
    
        NSImage *copiedImage = [template copy];
        [copiedImage setTemplate:NO];
        [copiedImage setSize:size];
    
        [copiedImage lockFocus];
    
        [tint set];
        NSRectFillUsingOperation(imageBounds, NSCompositeSourceAtop);
    
        [copiedImage unlockFocus];
    
        return [copiedImage autorelease];
    }