Core Text - NSAttributedString line height done right?

前端 未结 10 872
Happy的楠姐
Happy的楠姐 2020-12-23 09:21

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 - kCTParagraph

10条回答
  •  北海茫月
    2020-12-23 09:28

    There are two properties of NSParagraphStyle that modify the height between successive text baselines in the same paragraph: lineSpacing and lineHeightMultiple. @Schoob is right that a lineHeightMultiple above 1.0 adds additional space above the text, while a lineSpacing above 0.0 adds space below the text. This diagram shows how the various dimensions are related.

    To get the text to stay centred the aim is therefore to specify one in terms of the other, in such a way that any 'padding' we add by one attribute (top/bottom) is balanced by determining the other attribute's padding (bottom/top) to match. In other words, any extra space added is distributed evenly while otherwise preserving the text's existing positioning.

    The nice thing is that this way you can choose which attribute you want to specify and then just determine the other:

    extension UIFont
    {
        func lineSpacingToMatch(lineHeightMultiple: CGFloat) -> CGFloat {
            return self.lineHeight * (lineHeightMultiple - 1)
        }
    
        func lineHeightMultipleToMatch(lineSpacing: CGFloat) -> CGFloat {
            return 1 + lineSpacing / self.lineHeight
        }
    }
    

    From here, other answers show how these two attributes can be set in an NSAttributedString, but this should answer how the two can be related to 'centre' the text.

提交回复
热议问题