Search code examples
objective-cxcodemacosnsbutton

Custom NSButton with semi-transparent background


I'm trying to create a custom NSButton with a 50% opaque black background and white text. To do this I've subclassed NSButton and overloaded DrawRect:

- (void) drawRect:(NSRect)dirtyRect
{

    [self setBordered:NO];

    //REMED since it has same effect as NSRectFill below
    //[[self cell] setBackgroundColor:[NSColor colorWithCalibratedRed:0 green:0 blue:0 alpha:0.2]];

    NSColor* backgroundColor = [NSColor colorWithCalibratedWhite:0 alpha:0.3f];
    [backgroundColor setFill];
    NSRectFill(dirtyRect);

    [super drawRect:dirtyRect];
}

The white text appears fine but the button's background is always 100% opaque. The alpha value is not interpreted.

Any ideas? Thanks!


Solution

  • The default operation of NSRectFill() is copy which is not what you want. Replace it with

    NSRectFillUsingOperation(dirtyRect, NSCompositeSourceAtop);