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

fonts, ios, size, user-interface

Solution

OK, so for everyone who thinks an iteration is not avoidable:

NSString *string = @"The string to render";
CGRect rect = imageView.frame;

UIFont *font = [UIFont fontWithSize:12.0]; // find the height of a 12.0pt font
CGSize size = [string sizeWithFont:font];
float pointsPerPixel = 12.0 / size.height; // compute the ratio
// Alternatively:
// float pixelsPerPoint = size.height / 12.0;
float desiredFontSize = rect.size.height * pointsPerPixel;
// Alternatively:
// float desiredFontSize = rect.size.height / pixelsPerPoint;

`desiredFontSize` will contain the font size in points of which the height is exactly the same as the height of the specified rectangle. You may want to multiply it by, say, 0.8 to make the font a bit smaller than the rect's actual size to make it look good.

Problem

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.

Original source

Related problems