如何使用UIKit计算文本的确切高度? [英] How do I calculate the exact height of text using UIKit?

查看:135
本文介绍了如何使用UIKit计算文本的确切高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 - [NSString sizeWithFont] 来获取文本高度。字符't'明显比'm'高,但 -sizeWithFont 返回这两个字符串的相同高度。这里是代码:

I'm using -[NSString sizeWithFont] to get the text height. The character 't' is clearly taller than 'm', but -sizeWithFont returns the same height for both these strings. Here's the code:

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

如图所示,它返回 {834,1151} 。而 myStr = @t而是 {278,1151}

With 'm' as shown, it returns {834, 1151}. With myStr = @"t" instead, it's {278, 1151}. The smaller width shows up as expected, but not the height.

有没有其他函数包装文本?我理想地寻找等同于Android的Paint.getTextBounds()的东西。

Does some other function wrap the text tightly? I'm ideally looking for something equivalent to Android's Paint.getTextBounds().

推荐答案

嗯...我假设你只有使用单个字符然后。 sizeWithFont ,如上所述,返回该字体的最大字符的高度,因为无论你做什么,文本字段都将是该高度。你将能够得到最大高度值(UIFont的 CGFloat capHeight ),但它看起来像你将要处理各种文本

Hmmm... I assume you're only going to be working with individual characters then. sizeWithFont, as noted above, returns the height of the largest character of that font as the text field is going to be that height no matter what you do. You would be able to get the LARGEST height values (UIFont's CGFloat capHeight) however it looks like you're going to be working with all kinds of text

我会看看CoreText框架。开始这里并读取。不可避免地,你最终会得到类似这样的东西:

I would take a look at the CoreText framework. Start here and read away. Inevitably you're going to end up with something along the lines of this:

CGFloat GetLineHeightForFont(CTFontRef iFont)
{
    CGFloat lineHeight = 0.0;

    check(iFont != NULL);
    lineHeight += CTFontGetLeading(iFont);
    return lineHeight;
}

这篇关于如何使用UIKit计算文本的确切高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆