*准确*计算可可中的文本高度(适用于Mac,不适用于iOS)

编程入门 行业动态 更新时间:2024-10-26 08:25:50
本文介绍了*准确*计算可可中的文本高度(适用于Mac,不适用于iOS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

对于给定的固定宽度,如何计算特定标签(NSTextField)中字符串的高度?

How can I calculate the height of a string within a particular label (NSTextField), for some given fixed width?

我用Google搜索了各种方法,并尝试了苹果公司的这种方法.它的工作原理是,高度对于较短的字符串来说太短了一行.因此,目前的方法似乎存在一些误差.

I Googled up various methods and tried this method from Apple. It works, except that the height becomes one line too short for longer strings. Thus, there appear to be some inaccuracies in the present methods.

我在Google上搜索过的其他一些代码也遇到了同样的问题.

I also had the same issue with some other code I Googled up.

这里的某人是否有任何准确的代码来查找文本高度(给定的特定宽度)?

Does someone here have any accurate code for finding text height (given a particular width)?

推荐答案

我使用了 www.sheepsystems/sourceCode/sourceStringGeometrics.html 在该类别的头文件中,可以很好地解释这些工作原理.具体来说,他们提到应该使用NSTextView而不是NSTextField,因为要获得后者的准确高度实际上是不可能的.

I solved the problem using the NS(Attributed)String+Geometrics category provided at www.sheepsystems/sourceCode/sourceStringGeometrics.html Within the header file of that category is a good explanation of how these things work. Specifically, they mention that one should use NSTextView instead of NSTextField because it's virtually impossible to get an accurate height for the latter.

因此,我将NSTextField替换为NSTextView.首先,使用以下代码使NSTextView看起来像我的NSTextField:

Thus, I replaced my NSTextField with NSTextView. First, I made my NSTextView look like my NSTextField with this code:

[textView setEditable:YES]; [textView insertText:someString]; [textView setFont:[NSFont fontWithName:@"Lucida Grande" size:11] range:NSMakeRange(0,[someString length])]; [textView setEditable:NO]; [textView setSelectable:NO];

然后我得到了这段代码的高度:

Then I got the height with this code:

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: [textView font],NSFontAttributeName,nil]; NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString: [textView string] attributes:attributes]; CGFloat height = [attributedString heightForWidth: [textView frame].size.width];

对于NSTextView来说,高度确实是准确的.

The height does indeed turn out to be accurate for NSTextView.

我可能省略了一些小细节,但是您知道了.我希望这对外面的人有帮助.

I may have omitted some minor details, but you get the picture. I hope this helps someone out there.

更多推荐

*准确*计算可可中的文本高度(适用于Mac,不适用于iOS)

本文发布于:2023-11-27 08:43:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637332.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:适用于   可可   不适用于   文本   高度

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!