CGFontGetGlyphBBoxes 错误的结果

CGFontGetGlyphBBoxes wrong result

我一直在尝试精确测量字形边界,但这段代码打印出 916!!!这个的实际宽度是69.

- (void)drawRect:(NSRect)dirtyRect {
        CGContextRef main = [[NSGraphicsContext currentContext] graphicsPort];
        CGContextSetTextMatrix(main, CGAffineTransformIdentity);
        CGGlyph g;
        CGPoint p  = CGPointMake(100, 100);
        CGRect rect = CGRectMake(0, 0, 0, 0);
        CGFontRef font = CGFontCreateWithFontName((CFStringRef)@"Arial");
        g = CGFontGetGlyphWithGlyphName(font, CFSTR("L"));
        CGContextSetFont(main, font);
        CGContextSetTextPosition(main, 0, 0);
        CGContextSetFontSize(main, 200);
        CGContextSetRGBFillColor(main, 0, 0, 1, 1);
        CGContextShowGlyphsAtPositions(main, &g, &p, 1);
        CGFontGetGlyphBBoxes(font, &g, 1, &rect);
        printf("%f", rect.size.width);
    }

您正在使用 CGFontGetGlyphBBoxes,returns 大小 字形 space 单位。要使用它,您需要使用每 em 的单位和字体大小对其进行缩放。

CGRect rect;
CGFontRef font = CGFontCreateWithFontName((CFStringRef)@"Arial");
CGFloat fontSize = 200.0;
CGGlyph g = CGFontGetGlyphWithGlyphName(font, CFSTR("L"));
CGFontGetGlyphBBoxes(font, &g, 1, &rect);
CGFloat width = rect.size.Width / CGFontGetUnitsPerEm(font) * fontSize;

另一种方法是使用 [NSFont boundingRectForCGGlyph:]

NSFont *font = [NSFont fontWithName:@"Arial" size:200];
NSRect rect = [font boundingRectForCGGlyph:g];

boundingRectForCGGlyph
Returns the bounding rectangle for the specified glyph, scaled to the receiver’s size.