views:

477

answers:

2

I'm looking for the best way to change the background color of an NSView. I'd also like to be able to set the appropriate alpha mask for the NSView. Something like:

myView.backgroundColor = [NSColor colorWithCalibratedRed:0.227f green:0.251f blue:0.337 alpha:0.8];

I notice that NSWindow has this method, and I'm not a big fan of the NSColorWheel, or NSImage background options, but if they are the best, willing to use.

+2  A: 

Think I figured out how to do it:

- (void)drawRect:(NSRect)dirtyRect {
    // Fill in background Color
    CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
    CGContextSetRGBFillColor(context, 0.227,0.251,0.337,0.8);
    CGContextFillRect(context, dirtyRect);
}
BadPirate
+2  A: 

Yeah, you're own answer was right. You could also use cocoa methods:

- (void)drawRect:(NSRect)dirtyRect {
    // set any NSColor for filling, say white:
    [[NSColor whiteColor] setFill];
    NSRectFill(dirtyRect);
}
Mo
`NSRectFill` uses `NSCompositeCopy` to do the fill, so it'll clobber anything behind it—it won't composite on top of any ancestor views. For fills with a partially- (or fully-)transparent color, use `NSRectFillUsingOperation` http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ApplicationKit/Miscellaneous/AppKit_Functions/Reference/reference.html#//apple_ref/c/func/NSRectFillUsingOperation with the `NSCompositeSourceOver` operation.
Peter Hosey
Oh, that makes sense. I tried NSRectFill but the transparency didn't work. I'm coming to Cocoa from Cocoa Touch, and surprised to see that in some ways the Cocoa Touch framework is more complete (!). I was thinking of making a class extension for NSView that would allow you to set backgroundColor like you can an NSWindow or UIView, but I don't think you can override drawRect with an extension.
BadPirate
Sorry I missed the transparency part. Yeah, Cocoa touch makes many things easier. If you're also doing Cocoa touch your own answer is actually better, as it's more portable.
Mo