Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the height of the text rectangle from an NSString?

I know there is this one:

sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:

But since the CGSize always has the same height and doesn't adjust to any shrinked text or whatsoever, the CGSize is not telling how heigh the text is.

Example: Make a UILabel with 320 x 55 points and put a loooooooooooooong text in there. Let the label shrink the text down. Surprise: CGSize.height remains the same height even if the text is so tiny that you need a microscope.

Ok so after banging my head against my macbook pro which is half way broken now, the only think that can help is that nasty actualFontSize. But the font size is in pica I think, it's not really what you get on the screen, isn't it?

When that font size is 10, is my text really 10 points heigh at maximum? Once in a while I tried exactly that, and as soon as the text had a y or some character that extends to below (like that tail of an y does), it is out of bounds and the whole text is bigger than 10 points.

So how would you calculate the real text height for a single line uilabel without getting a long beard and some hospital experience?

like image 399
dontWatchMyProfile Avatar asked Apr 23 '10 11:04

dontWatchMyProfile


People also ask

How do you measure text height?

Multiply the drawing scale factor by the desired text output height to determine the height of the text objects in the drawing. Using the drawing scale factor of 48 and a desired text height of 3/16” for the output, you would take 48 x 0.1875 to get a final text height of 9.

How is font width calculated?

The calculation of font size as prescribed in DIN 1450 is based on x-heights. Font size (here x-height) is generally set depending on the viewer's distance from it. The shorter a viewer's distance from a text is, the smaller its font can be and vice-versa.


2 Answers

Try this code:

CGSize maximumSize = CGSizeMake(300, 9999);
NSString *myString = @"This is a long string which wraps";
UIFont *myFont = [UIFont fontWithName:@"Helvetica" size:14];
CGSize myStringSize = [myString sizeWithFont:myFont 
    constrainedToSize:maximumSize 
    lineBreakMode:self.myLabel.lineBreakMode];

from my answer here

It uses a different method, and sets up a very high CGSize at the start (which is then shrunk to fit the string)

like image 131
nevan king Avatar answered Oct 06 '22 00:10

nevan king


Important: As of iOS 7.0 the following method is deprecated.

sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:

Use the below code instead

CGRect frame = [cellText boundingRectWithSize:CGSizeMake(568,320) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:32.0f]} context:nil];
float height = frame.size.height;
like image 24
thandasoru Avatar answered Oct 06 '22 00:10

thandasoru