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

查看:500
本文介绍了如何获得固定宽度的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选项:(NSStringDrawingOptions)选项使用一个rect形状到我想要的宽度和 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-ish太短))。

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) / code>

,但传入的 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天全站免登陆