如何以固定宽度获取 NSAttributedString 的高度 [英] How to get height for NSAttributedString at a fixed width

查看:18
本文介绍了如何以固定宽度获取 NSAttributedString 的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在固定宽度的框中绘制一些 NSAttributedStrings,但是在计算绘制时它们将占用的正确高度时遇到了麻烦.到目前为止,我已经尝试过:

I want to do some drawing of NSAttributedStrings in fixed-width boxes, but am having trouble calculating the right height they'll take up when drawn. So far, I've tried:

  1. 调用 - (NSSize) size,但结果没有用(为此目的),因为它们会给出字符串所需的任何宽度.

  1. Calling - (NSSize) size, but the results are useless (for this purpose), as they'll give whatever width the string desires.

调用 - (void)drawWithRect:(NSRect)rect options:(NSStringDrawingOptions)options 用一个矩形形状为我想要的宽度和 NSStringDrawingUsesLineFragmentOrigin 在选项,与我在绘图中使用的完全一样.结果……难以理解;当然不是我要找的.(正如许多地方所指出的,包括this Cocoa-Dev 线程).

Calling - (void)drawWithRect:(NSRect)rect options:(NSStringDrawingOptions)options with a rect shaped to the width I want and NSStringDrawingUsesLineFragmentOrigin in the options, exactly as I'm using in my drawing. The results are ... difficult to understand; certainly not what I'm looking for. (As is pointed out in a number of places, including this Cocoa-Dev thread).

创建一个临时的 NSTextView 并执行:
[[tmpView textStorage] setAttributedString:aString];
[tmpView setHorizo​​ntallyResizable:NO];
[tmpView sizeToFit];

当我查询 tmpView 的框架时,宽度仍然是所需的,并且高度通常是正确的......直到我得到更长的字符串时,它通常是所需大小的一半.(似乎没有达到最大尺寸:一帧高 273.0(约 300 太短),另一帧是 478.0(只有 60 左右太短)).

Creating a temporary NSTextView and doing:
[[tmpView textStorage] setAttributedString:aString];
[tmpView setHorizontallyResizable:NO];
[tmpView sizeToFit];

When I query the frame of tmpView, the width is still as desired, and the height is often correct ... until I get to longer strings, when it's often half the size that's required. (There doesn't seem to be a max size being hit: one frame will be 273.0 high (about 300 too short), the other will be 478.0 (only 60-ish too short)).

如果有其他人解决了这个问题,我将不胜感激.

I'd appreciate any pointers, if anyone else has managed this.

推荐答案

答案使用
- (void)drawWithRect:(NSRect)rect options:(NSStringDrawingOptions)options
但是你传入的 rect 在你想要无限的维度上应该有 0.0(呃,这很有意义).示例 此处.

The answer is to use
- (void)drawWithRect:(NSRect)rect options:(NSStringDrawingOptions)options
but the rect you pass in should have 0.0 in the dimension you want to be unlimited (which, er, makes perfect sense). Example here.

这篇关于如何以固定宽度获取 NSAttributedString 的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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