View Full Version : Exact style for NSMenuItem?

Feb 6, 2012, 03:13 PM
I'm trying to get my NSMenuItem to have the exact same font/style as the default ones, but I'm having troubles.

Here's my code:
NSDictionary *attributeDictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"LucidaGrande" size:13.0], NSFontAttributeName, nil];
statusItem.attributedTitle = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@" Mon Feb 6"] attributes:attributeDictionary];

I've attached the output below. On the far left is my menu item. On the far right is the built in date / time menu item I'm trying to copy.

It's close, but not quite right. It's what I was told was the proper font, but it actually looks to me like what was the proper font several OS versions ago (10.4?) It looks a little too sharp... it should be slightly taller and slightly wider. Making it the next size up makes it too tall. Making it bold... actually, I haven't figured out how to bold it (I've tried adding "-bold" to the end of the name of the font, but that seems to result in getting a completely unrelated font to show up...)

Edit: Adding a shadow with offset of 0.5, 0.5 seems a little promising... it doesn't look quite right, though...

Feb 6, 2012, 10:17 PM
I played around with a few ideas, and this seems to get the best results. It seems turning off CGContextSetShouldSmoothFonts() makes it look better.

NSTextFieldCell *cell = [[[NSTextFieldCell alloc] initTextCell:text] autorelease];
[cell setDrawsBackground:NO];
[cell setFont:font];
[cell setBackgroundStyle:NSBackgroundStyleRaised];

NSSize cellSize = [cell cellSize];
NSSize imgSize = NSMakeSize(floor(cellSize.width), [[NSStatusBar systemStatusBar] thickness]);
NSImage *img = [[NSImage alloc] initWithSize:imgSize];
[img lockFocus];
NSRect bounds = NSMakeRect(0, 0, imgSize.width, imgSize.height);
CGContextRef ctx = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
CGContextSetShouldSmoothFonts(ctx, false);
NSRect cellRect = NSMakeRect(0, (bounds.size.height - cellSize.height) / 2, cellSize.width, cellSize.height);
[cell drawWithFrame:cellRect inView:nil];
[img unlockFocus];

[statusItem setImage:img];

Feb 7, 2012, 06:21 AM
I'm surprised Apple hasn't actually told developers how to make text that fits in with the rest of the status items... thanks for your help, I think this is going to work :)