How to calculate exact text height using UIKit?

I use -[NSString sizeWithFont] to get the height of the text. The character 't' is clearly higher than 'm', but -sizeWithFont returns the same height for both of these lines. Here is the code:

 UIFont* myFont = [UIFont fontWithName:@"Helvetica" size:1000.0]; NSString* myStr = @"m"; CGSize mySize = [myStr sizeWithFont:myFont]; 

With 'm', as shown, it returns {834, 1151} . Instead of myStr = @"t" it is {278, 1151} . Smaller widths are displayed as expected, but not height.

Is there any other function used for dense text wrapping? I am ideally looking for something that is equivalent to Android Paint.getTextBounds ().

+4
source share
2 answers

Hmmm ... I assume that you will only work with individual characters. sizeWithFont , as noted above, returns the height of the largest character in this font, since the text box will be that height no matter what you do. You could get the largest height values ​​(UIFont CGFloat capHeight ), but it looks like you will work with all types of text

I would look at the structure of CoreText. Start here and read. Inevitably you will get something like this:

 CGFloat GetLineHeightForFont(CTFontRef iFont) { CGFloat lineHeight = 0.0; check(iFont != NULL); lineHeight += CTFontGetLeading(iFont); return lineHeight; } 
+1
source

The information you get from this method is basically the line height for the font (i.e., ascension plus descent for the selected font). It is not based on individual characters, it is based on specific font metrics. You can get most of the font metrics information from the UIFont class (for example, the -ascender method gives you the height of the splash screen for the font). Basically, you will be dealing with the total amount of vertical space needed to draw glyphs with heights and the smallest descenders for this font. Unable to retrieve information about individual glyphs from UIFont. If you need this information, you will need to look at the CoreText structure, which will give you much more flexibility in how you draw and place glyphs, but much more difficult to use.

For more information about using text in an application, see the β€œDrawing and Text Management” section of the Programming Guide for Text, Web, and Editing . It is also a good starting point for most of the frameworks and classes you will need if you take the UIKit or CoreText route.

+3
source

Source: https://habr.com/ru/post/1389563/


All Articles