How to get height for NSAttributedString at a fixed width

Posted by bonaldi on Stack Overflow See other posts from Stack Overflow or by bonaldi
Published on 2010-02-17T16:53:07Z Indexed on 2010/03/17 5:41 UTC
Read the original article Hit count: 300

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. Calling - (NSSize) size, but the results are useless (for this purpose), as they'll give whatever width the string desires.

  2. 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).

  3. 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.

© Stack Overflow or respective owner

Related posts about cocoa

Related posts about appkit