iOS – 获得一个字母的“真实”高度

我正在尝试在UIView上布局文本。

(黄色区域是具有背景颜色的UILabel的框架)。

当我使用sizeWithFont我得到这个,它有一个非常大的空间上面的信件:

与sizeWithFont的p

当我使用font.pointSize我得到这个“我”这是很好的,

p与font.pointSize

但是,当我使用它的“P”我得到了确切的高度,但字母是在底部绘制和裁剪。

p与font.pointSize

**我怎样才能得到只在框架中心的字形? **

谢谢

沙尼

UIFont上有很多属性可以帮助解决这种情况:

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

您可以将UILabel转换为具有“printscreen”function的UIImage ,然后逐个检查像素(例如: 如何从UIImage(Cocoa Touch)或CGImage(Core Graphics)获取像素数据? )并“计算”左上angular和右下angular。

尝试通过font.ascender – font.capHeight向上移动文本。 缩小UILabel的高度可能会限制其内容,所以最好调整标签的y位置而不是resize。

以下代码示例介绍了我使用的计算:

 // 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; }