iOS - Get the “real” height of a letter

与世无争的帅哥 提交于 2019-12-03 11:05:10

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

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

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.

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