How to get height for NSAttributedString at a fixed width

后端 未结 12 1129
萌比男神i
萌比男神i 2020-12-12 18:53

I want to do some drawing of NSAttributedStrings in fixed-width boxes, but am having trouble calculating the right height they\'ll take up when drawn. So far, I\'ve tried:

12条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-12 19:38

    I just wasted a bunch of time on this, so I'm providing an additional answer to save others in the future. Graham's answer is 90% correct, but it's missing one key piece:

    To obtain accurate results with -boundingRectWithSize:options: you MUST pass the following options:

    NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesDeviceMetrics|NSStringDrawingUsesFontLeading
    

    If you omit the lineFragmentOrigin one, you'll get nonsense back; the returned rect will be a single line high and won't at all respect the size you pass into the method.

    Why this is so complicated and so poorly documented is beyond me. But there you have it. Pass those options and it'll work perfectly (on OS X at least).

提交回复
热议问题