Retina显示屏的字体大小

3

我的Mac OS应用程序使用以下代码绘制一些文本:

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];
}

由于文本绘制只是应用程序的一小部分,因此到目前为止,这种简单的方法已经运作良好。但是现在随着新的Retina显示屏的出现,用户抱怨文本与其他图形相比显得太大。似乎给定绝对字体大小(我的情况下为9)不再起作用。

我该如何修改此代码,以便在Retina和非Retina显示屏上均可正常工作?

1个回答

3

字体大小以点为单位度量,而不是像素。因此,任何值都应该独立于Retina分辨率。例如,这段代码可以正常工作:

- (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 }];
}

结果:

非Retina

Retina

如果你有不同显示模式的精确像素大小,请尝试以下内容:

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];

能用吗?


我开始看到我的问题所在了:“因此,任何值都应该独立于Retina分辨率” - 我需要指定文本大小以像素为单位,以便与原始基于像素的图形匹配。 - Periodic Maintenance
1
虽然它的代码不完全如上所述,但它确实有效。我无法访问窗口,因此必须为主屏幕调用backingScaleFactor。此外,我正在使用SDK 10.6,并且backingScaleFactor仅可通过NSInvocation调用获得。 然而,基本思路是行得通的,我会接受这个答案。 谢谢! - Periodic Maintenance

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接