How to draw a native looking statusitem background on a CALayer
Actually I want to draw the background of a selected NSStatusItem
on the CALayer
of my custom statusItemView. But since
- (void)drawStatusBarBackgroundInRect:(NSRect)rect withHighlight:(BOOL)highlight
does not work (?) on layers I've tried it to draw the color with the backgroundColor property. But converting the selectedMenuItemColor into RGB doesn't help very much. It looks really plain without the gradient. :-/
I converted [NSColor selectedMenuItemColor]
into a CGColorRef
with this code:
- (CGColorRef)highlightColor {
static CGColorRef highlight = NULL;
if(highlight == NULL) {
CGFloat red, green, blue, alpha;
NSColor *hlclr = [[NSColor selectedMenuItemColor] colorUsingColorSpace:
开发者_如何学Python[NSColorSpace genericRGBColorSpace]];
[hlclr getRed:&red green:&green blue:&blue alpha:&alpha];
CGFloat values[4] = {red, green, blue, alpha};
highlight = CGColorCreate([self genericRGBSpace], values);
}
return highlight;
}
Any idea how to draw a native looking statusitem background on a CALayer?
NSImage *backgroundImage = [[NSImage alloc] initWithSize:self.frame.size]];
[backgroundImage lockFocus];
[self.statusItem drawStatusBarBackgroundInRect:self.bounds withHighlight:YES];
[backgroundImage unlockFocus];
[self.layer setContents:backgroundImage];
[backgroundImage release];
Try subclassing CALayer and implementing the drawInContext:
method to create an NSGraphicsContext for the CGContext, set the NSGraphicsContext as the current context, and then tell the status item to draw its background.
I use this code in my layer delegate:
- (void)drawLayer:(CALayer *)layer
inContext:(CGContextRef)context {
NSGraphicsContext* gc = [NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:NO];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:gc];
[self.statusItem drawStatusBarBackgroundInRect:self.frame
withHighlight:self.isHighlighted];
[NSGraphicsContext restoreGraphicsState];
}
精彩评论