Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting information about a glyph in Core Text

I just saw this recent question on SO, which gets somewhat close to what I'm asking here.

So I'm trying to typeset a mathematical equation using Core Text and NSAttributedString. It was working pretty well for expressions like x2, but then I came across a problem when I use y. Namely, 'y' has a descender which I don't know how to take into account in my drawing code:

CGContextSaveGState(context);
CGContextTranslateCTM(context, x, sizeOfGlyph.height / 2.0);
CGContextScaleCTM(context, 1.0, -1.0);

CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CTLineRef line = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)attributedSubstring);
CGContextSetTextPosition(context, 0.0, 0.0);
CTLineDraw(line, context);

CFRelease(line);
CGContextRestoreGState(context);

Basically, I translate the context by half the glyph's height (as calculated here) to start the text at the baseline of the glyph. As you can imagine, this runs into problems with glyphs like 'y', because half the glyph's height isn't the baseline of the glyph. I don't think it's sufficient to use the font's descender, because I have no way of knowing whether this glyph has a descender or not. So what I'd like to find out is whether there is a way to find the descender (or any desired metrics) for a particular glyph?

Any know-how on the topic would be appreciated, I'm just getting started with Core Text.

like image 706
architectpianist Avatar asked Apr 13 '14 21:04

architectpianist


1 Answers

What I ended up doing was to use the origin of the glyph returned from the image bounds function. I calculated the bounds of the glyph using the method outlined in this answer. The origin of the resulting CGRect gives the y-position of the glyph's bottom-left corner, which in the case of 'y' would be negative. So by adding together glyphRect.origin.y + glyphRect.size.height, you get the distance from the top of the glyph to the baseline.

like image 102
architectpianist Avatar answered Nov 11 '22 01:11

architectpianist