Christoffer
Christoffer

Reputation: 26825

+colorWithPatternImage: should preserve transparency in Cocoa

I have a custom NSView that is used for displaying a background color. This works. However, I have shadows in that image that are not preserved.

All transparent or semi-transparent areas of the image are rendered as black. How do I fix this?

- (void)drawRect:(NSRect)dirtyRect {
    NSColor *pattern = [NSColor colorWithPatternImage:[NSImage imageNamed:@"bg"]];
    [pattern setFill];
    NSRectFill(dirtyRect);
}

Thanks.

Upvotes: 3

Views: 450

Answers (1)

Rob Keniger
Rob Keniger

Reputation: 46020

NSRectFill() is a shortcut for NSRectFillUsingOperation(rect, NSCompositeCopy). This means that it won't composite the color's alpha channel with the background, it simply draws the source color in the rectangle you pass in. Instead, you should use:

NSRectFillUsingOperation(rect, NSCompositeSourceOver);

The NSCompositeSourceOver compositing operation will display the source image wherever the source image is opaque and the destination image elsewhere.

Upvotes: 6

Related Questions