NSString boundingRectWithSize略低估了正确的宽度 - 为什么? [英] NSString boundingRectWithSize slightly underestimating the correct width - why?

查看:209
本文介绍了NSString boundingRectWithSize略低估了正确的宽度 - 为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个类,显示一个带有一些文本的窗口,不再显示复选框和一个按钮。为了可重用,类根据需要调整窗口大小以适合文本。

I'm creating a class that displays a window with some text, a "Don't show again" checkbox and a button. In order to be reusable, the class resizes the window as needed to fit the text.

但是,在计算中有一些轻微的不精确 - 如果我不添加5像素到宽度一些字符串被截断。

However, there is some slight imprecision in the calculations - if I don't add 5 pixels to the width some strings are truncated. (The last word is simply removed.)

这里是我有的:

// NSTextField *textLabel;
// NSString *text;
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject: [textLabel font] forKey: NSFontAttributeName];
NSRect textFrame = [text boundingRectWithSize:NSMakeSize(textLabel.frame.size.width, (unsigned int)-1)
                                      options:(NSStringDrawingDisableScreenFontSubstitution | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
                                   attributes:stringAttributes];
textFrame.size.width += 5;

我暂时将标签的背景颜色设置为黄色,使调试更容易, em>几乎符合最后一个字。 4个像素额外的就足够了测试字符串。

请注意,并非所有字符串失败,没有这些添加的像素。

I temporarily set the label's background color to yellow to make the debugging easier, and it clearly expands to almost fit that last word. 4 pixels extra is enough on that test string.
Do note that not all strings fail without these added pixels.

有两个原因,我care:

1)我想知道为什么它有点错误,更重要的是

2)我想通过改变计算后的宽度,包装可以理论上改变

There are two reasons that I care:
1) I want to learn why it's slightly wrong, and more importantly
2) I'm figuring that by changing the width after the calculation, the wrapping can theoretically change and leave the otherwise last line unused, creating extra empty space below the text.

推荐答案

使用ceilf()覆盖结果,以便值将舍入为下一个整数。这是一个很大的区别。

Wrap the result with ceilf() so the value is rounded up to the next whole number. That makes a big difference.

这篇关于NSString boundingRectWithSize略低估了正确的宽度 - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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