Lexandr
Lexandr

Reputation: 689

Sometimes wrong size of multiline string


I try to find size of certain string using following code:

NSAttributedString *attributedString = ...// Actually system font, 13 pt.
NSSize size = ...// Actually more than string size
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithContainerSize:size];
[textContainer setLineFragmentPadding:0.0];

NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[layoutManager setTypesetterBehavior:NSTypesetterBehavior_10_2_WithCompatibility]; // Setting up different typeSetterBehavior would not fixes the size issue
[layoutManager addTextContainer:textContainer];

NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attributedString];
[textStorage addLayoutManager:layoutManager];

// Layout manager performs layout lazily, force it to lay out the text
[layoutManager glyphRangeForTextContainer:textContainer];

NSSize textSize = [layoutManager usedRectForTextContainer:textContainer].size;

And at that point, textSize for some strings! less then string need. For example, for "Doesn't look like a string value." string in returned size can be drawn only "Doesn't look like a string", but for @"Doesn't look like a string value. This is a number." string all ok.

Wrong size Normal size

All same happens when I receive string size with:

[attributedString boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin].size

or

NSRange glyphRange = [layoutManager glyphRangeForTextContainer:textContainer];
NSSize textSize = [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer].size;

Can anyone explain me why for some string I receive wrong size?
Thanks.

Upvotes: 1

Views: 981

Answers (1)

Wil Shipley
Wil Shipley

Reputation: 9553

I’m guessing when you create the views that are displaying the text, you’re ignoring that NSTextField and NSTextView both have their text inset a bit from their frames.

If you’re using a textView, for instance, set the textContainerInset to NSZeroSize and see if that works better.

Upvotes: 4

Related Questions