How does CTFontGetAdvancesForGlyphs work?

276 views Asked by At

The CoreText method CTFontGetAdvancesForGlyphs adds the advances for all glyphs of an array of such and returns the sum.

However, if the array consists only of 1 element:

var offset = CCTFontGetAdvancesForGlyphs(myFont, .default, &myGlyph, nil, 1)

is calling the method just performing a simple lookup like when I access a variable, or will it trigger some kind of calculation on each call?

I'm wondering whether I need to store the result in a constant when I need the width of some specific glyphs repeatedly.

1

There are 1 answers

0
Agam On

Take a look at these lines, this may help to understand the use of the function:

CGGlyph* glyphs = new CGGlyph[count];
CGSize*  advs   = new CGSize[count];

BOOL  ret = CTFontGetGlyphsForCharacters(fntRef, buffer, glyphs, count);
float sum = CTFontGetAdvancesForGlyphs  (fntRef, kCTFontOrientationHorizontal, glyphs, advs, count);
  • buffer contains your string of characters (UniChar)
  • the call to CTFontGetGlyphsForCharacters will fill the array glyphs.
  • the call to CTFontGetAdvancesForGlyphs will fill the array advs with the width of each glyph.

You can now do the following:

CGPoint* positions   = new CGPoint[count];
for(int i=0;i<count;++i) {
    positions[i] = CGPointMake(x, y);
    x += advs[i].width + someAdditionalOffset;
}
CGContextShowGlyphsAtPositions(context, glyphs, positions, count);

Your string of characters will be displayed according to the positions x,y you set for each character. This set of functions is very useful for creating custom alignments, custom kerning etc.