Search code examples
iosswiftios8nsattributedstringcgsize

Get string baseline position within its bounding box


I have been using sizeWithAttributes in order to obtain the width and height required in order to draw an NSAttributedString. This is working well to get the width because the value returned for width fits the characters very snuggly - it's calculated from the first character to the last without any additional padding added. But for height, it's returning a value larger than I would like. This is because it must calculate the height starting at the top of the tallest letter and extending down to the bottom of the lowest character - for example the g character extends below the baseline.

I don't believe this API is 'intelligent' because none of the characters in my string extend below the baseline, yet the height returned is too tall. It seems to be considering any possible character that could be displayed with those attributes.

I am in need of a way to subtract the amount of "extra padding" below the string. I want to calculate where the baseline is relative to the height, or some other way to calculate how much space is dedicated to the area beneath the baseline. The illustration below explains visually what I believe to be occurring, although the padding amount is a little extreme.

-------------

--greetings--
              <-get rid of this 'extra' padding
-------------

I believe boundingRectWithSize:options:context: would give me the same dimensions, and I'm not aware of any other (non-deprecated) API that calculates string sizes.


Solution

  • UIFont has the attributes ascender (height above the baseline) and descender (negative, height below the baseline). This is probably what you are looking for.