olaf
olaf

Reputation: 73

CGGlyphs wrong position

I have been trying to draw single glyph with core text, but the x position of letter is little bit different. The red rectangle show the correct position.

CGContextRef main = [[NSGraphicsContext currentContext] graphicsPort];
    CGContextSetAllowsAntialiasing(main, false);

    CGContextSetFont(main, font);
    CGContextSetFontSize(main, 200);
    CGContextSetTextPosition(main, 0, 0);

    glyphs[0] =  CGFontGetGlyphWithGlyphName(font, CFSTR("E"));
    points[0] = CGPointMake(100, 100);

    CGContextSetRGBFillColor(main, 0, 1, 0, 1);
    CGContextShowGlyphsAtPositions(main, glyphs, points, 1);

    CGRect *r = malloc(sizeof(CGRect)*1);
    CGFontGetGlyphBBoxes(font, glyphs, 1, r);
    float t = roundf(r[0].size.width/CGFontGetUnitsPerEm(font)*200);
    float t2 = roundf(r[0].size.height/CGFontGetUnitsPerEm(font)*200);
    CGRect r2 = CGRectMake(points[0].x, points[0].y-1, t, t2+2);
    CGContextSetRGBStrokeColor(main, 1, 0, 0, 1);
    CGContextStrokeRect(main, r2);

Here is screenshot:

enter image description here

Upvotes: 1

Views: 83

Answers (1)

Rob Napier
Rob Napier

Reputation: 299355

You're assuming the bounding box's origin is at zero. It isn't. You need to add in its offset. Something like (following your patterns):

float cornerX = roundf(r[0].origin.x/CGFontGetUnitsPerEm(font)*200);
float cornerY = roundf(r[0].origin.y/CGFontGetUnitsPerEm(font)*200);

CGRect r2 = CGRectMake(points[0].x+cornerX, points[0].y-1+cornerY, t, t2+2);

Upvotes: 1

Related Questions