Several posts have noted difficulties with getting an exact height out of CTFramesetterSuggestFrameSizeWithConstraints, and here, (framesetter post), @Chris DeSalvo gives what looks like the definitive fix: add a paragraph style setting with the correct line spacing adjustment.
DeSalvo gets his “leading” by removing UIFont’s ascender and descender from its lineHeight. I wondered how that would compare to CTFontGetLeading
.
I worked with fonts created like this:
CTFontRef fontr = CTFontCreateWithName((CFStringRef)@"Helvetica Neue", 16.0f, NULL);
UIFont *font = [UIFont fontWithName:@"Helvetica Neue" size:16.0f];
The values were quite different:
- 0.448 CTFontGetLeading
- 2.360 DeSalvo’s formula: UIFont lineHeight - ascender + descender
Here are some other UIFont values:
- 21.000 UIFont’s lineHeight
- 15.232 UIFont’s ascender (Y coord from baseline)
- -3.408 UIFont’s descender (Y coord from baseline)
- 08.368 UIFont’s xHeight
And here are the CTFont values that Ken Thomases inquired about:
- 11.568001 CTFontGetCapHeight
- 08.368 CTFontGetXHeight
- -15.216001, -7.696001, 38.352001, 24.928001 CTFontGetBoundingBox
- 15.232 CTFontGetAscent
- 03.408 CTFontGetDescent (class ref says "scaled font-descent metric scaled according to the point size and matrix of the font reference" -- which apparently means that it is the absolute value of the Y coordinate from the baseline?)
I note that UIFont previously had a property specifically for “leading,” but it has been deprecated and we are advised to use lineHeight
instead. So UIFont considers leading to be 21 and CTFontRef .448 for the same font? Something’s not right.
Three questions:
- Is “leading” really what is meant by kCTParagraphStyleSpecifierLineSpacingAdjustment?
- If so, which method/formula should I use to get it?
- If not, what should I use for the line spacing adjustment?
Answers to the 3 questions I had above:
CTFontGetLeading(fontRef)
to get the font's normal leading, or plug in whatever value (as a CGFloat) you choose.Answers 1 and 2 work: Specifying a leading value in a paragraphStyle attribute of your attributed string will enable the Core-Text framesetter to calculate its height exactly.
There are two caveats:
And there is one mystery: What is going on with UIFont's deprecated leading? Leading and lineHeight are two distinct things.