3
votes

My Mac OS application draws some text using code like this:

void drawString(NSString* stringToDraw)
{
    NSFontManager *fontManager = [NSFontManager sharedFontManager];
    NSString* fontName =  [NSString stringWithCString: "Helvetica" encoding: NSMacOSRomanStringEncoding];
    NSFont* font = [fontManager fontWithFamily:fontName traits:0 weight:5 size:9];
    NSMutableDictionary *attribs = [[NSMutableDictionary alloc] init];
    [attribs setObject:font forKey:NSFontAttributeName];
    [stringToDraw drawAtPoint:NSMakePoint (0, 0) withAttributes:attribs];
}

Since text drawing is very small part of the application this simple approach has worked well so far. But now with the new retina display, users complain that the text appears too big compare to the rest of the graphics. It seems that giving an absolute font size (9 in my case) no longer works.

How can I fix this code so that it works well for both retina and non-retina displays?

1

1 Answers

3
votes

Font size is measured in points, not in pixels. So any value should be independent of Retina resolution. For example, this code works okay:

- (void)drawRect:(NSRect)dirtyRect
{
    CGRect textRect = CGRectInset(self.bounds, 15.0, 15.0);

    [[[NSColor whiteColor] colorWithAlphaComponent:0.5] setFill];
    NSRectFillUsingOperation(textRect, NSCompositeSourceOver);

    NSFont *font = [[NSFontManager sharedFontManager] fontWithFamily:@"Helvetica"
                                                              traits:0.0
                                                              weight:5.0
                                                                size:30.0];
    [@"Hello\nWorld" drawInRect:textRect
                 withAttributes:@{ NSFontAttributeName : font }];
}

Results:

Non-retina

Retina

If you have precise pixel sizes for different display modes, try something like this:

CGFloat contentsScale = self.window.backingScaleFactor;
CGFloat fontSize = (contentsScale > 1.0 ? RETINA_FONT_SIZE : STANDARD_FONT_SIZE);
NSFont *font = [[NSFontManager sharedFontManager] fontWithFamily:@"Helvetica"
                                                          traits:0.0
                                                          weight:5.0
                                                            size:fontSize];

Does it work?