Core Text - NSAttributedString line height done right?

Schoob picture Schoob · Nov 15, 2011 · Viewed 59.9k times · Source

I'm completely in the dark with Core Text's line spacing. I'm using NSAttributedString and I specify the following attributes on it: - kCTFontAttributeName - kCTParagraphStyleAttributeName

From this the CTFrameSetter gets created and drawn to context.

In the paragraph style attribute I'd like to specify the height of the lines.

When I use kCTParagraphStyleSpecifierLineHeightMultiple each line receives padding at the top of the text, instead of the text being displayed in the middle of this height.

When I use kCTParagraphStyleSpecifierLineSpacing a padding is added to the bottom of the text.

Please help me achieve a specified line height with the text(glyphs) in the middle of that height, instead of the text sitting either at the bottom or the top of the line.

Is this not possible without going down the route of explicitly creating CTLine 's and so forth?

Answer

Tieme picture Tieme · May 2, 2013

Objective-C

NSInteger strLength = [myString length];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:24];
[attString addAttribute:NSParagraphStyleAttributeName
                  value:style
                  range:NSMakeRange(0, strLength)];

Swift 5

let strLength = myString.length()
var style = NSMutableParagraphStyle()
style.lineSpacing = 24
attString.addAttribute(.paragraphStyle, value: style, range: NSRange(location: 0, length: strLength))