iOS - Get the “real” height of a letter

非 Y 不嫁゛ 提交于 2019-12-04 17:18:57

问题


I am trying to layout text on a UIView.

(The yellow area is the frame of the UILabel with a background color).

When I use sizeWithFont I get this, which has a very large space above the letter:

When I use font.pointSize i get this for "i" which is good-

BUT When i use it for "p" I get the precise height but the letter is drawn in the bottom and cropped.

**How can i get get the glyph only centered in the frame ? **

Thanks

Shani


回答1:


There are a lot of properties on UIFont to help in this situation:

  • pointSize
  • ascender
  • descender
  • capHeight
  • xHeight
  • lineHeight



回答2:


You could convert the UILabel to a UIImage with a "printscreen" sort of function and then check the the pixels one by one (with for instance: How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?) and 'calculate' the left top en right bottom.




回答3:


Try moving the text upwards by font.ascender - font.capHeight. Shrinking the height of a UILabel will likely clip its contents, so it is better to adjust the label's y position instead of resizing.

The following code sample explains the computation I used:

// in UILabel subclass:
- (CGFloat) topPadding
{
    // ascender = height from baseline to top of label (including top padding)
    // capHeight = height of a capital letter = ascender - top padding
    //  -> top padding = ascender - capHeight
    return self.font.ascender - self.font.capHeight;
}


来源:https://stackoverflow.com/questions/9020246/ios-get-the-real-height-of-a-letter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!