iOS - How to find the right font size (in points) with the same height as a given CGRect?

11,119

From here

http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/CoreText_Programming/Operations/Operations.html

CGFloat GetLineHeightForFont(CTFontRef iFont)
{
    CGFloat lineHeight = 0.0;

    check(iFont != NULL);

    // Get the ascent from the font, already scaled for the font's size
    lineHeight += CTFontGetAscent(iFont);

    // Get the descent from the font, already scaled for the font's size
    lineHeight += CTFontGetDescent(iFont);

    // Get the leading from the font, already scaled for the font's size
    lineHeight += CTFontGetLeading(iFont);

    return lineHeight;
}

To use this, guess a point size, find it's line height (you may or may not care about leading). Then use the ratio between the answer and the height you have to scale the point size. I don't think you're guaranteed that the height will be exactly right -- if you care about it being exact, you have to iterate until it's close enough (use the new size as the new guess).

Share:
11,119
sparkFinder
Author by

sparkFinder

Updated on June 12, 2022

Comments

  • sparkFinder
    sparkFinder almost 2 years

    Heading pretty much explains it. I have an image that I'm drawing text on. I want the text to be sized according to the size of the image and want to find a way to get a height for the font that is just a little shorter than the image itself.