I want to take a standard UILabel and increase the font size so that it fills the vertical space. Taking inspiration from the accepted answer for this question, I defined a sub
I wonder if its a rounding error inching up to the next larger font size. Could you just scale the rec.size.height slightly? Something like:
float desiredPointSize = rect.size.height *.90 * pointsPerPixel;
Update: Your pointPerPixel calculation is backwards. You're actually dividing pixels by font points, instead of points by Pixels. Swap those and it works every time. Just for thoroughness, here's the sample code I tested:
//text to render
NSString *soString = [NSString stringWithFormat:@"{Hg"];
UIFont *soFont = [UIFont fontWithName:@"Helvetica" size:12];
//box to render in
CGRect rect = soLabel.frame;
//calculate number of pixels used vertically for a given point size.
//We assume that pixel-to-point ratio remains constant.
CGSize size = [soString sizeWithFont:soFont];
float pointsPerPixel;
pointsPerPixel = soFont.pointSize / size.height; //this calc works
//pointsPerPixel = size.height / soFont.pointSize; //this calc does not work
//now calc which fontsize fits in the label
float desiredPointSize = rect.size.height * pointsPerPixel;
UIFont *newFont = [UIFont fontWithName:@"Helvetica" size:desiredPointSize];
//and update the display
[soLabel setFont:newFont];
soLabel.text = soString;
That scaled and fit inside the label box for every size I tested, ranging from 40pt to 60pt fonts. When I reversed the calculation, then I saw the same results with the font being too tall for the box.