CGFontGetGlyphBBoxes wrong result

纵然是瞬间 提交于 2019-12-11 17:05:34

问题


I have been trying to measure glyph bounds precisely but this code prints out 916!!! The real width of this is 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);
    }

回答1:


You are using CGFontGetGlyphBBoxes, which returns the size in glyph space units. To use this, you need to scale it with the units per em and the font size.

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;

An alternate way to do it to use [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.



来源:https://stackoverflow.com/questions/50375654/cgfontgetglyphbboxes-wrong-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!