1
我嘗試使用下面的代碼查找特定字符串的大小:多串有時錯誤的大小
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;
而在這一點上,textSize
對於一些字符串!少於字符串需要。例如,對於「看起來不像字符串值」。返回大小的字符串只能繪製「看起來不像字符串」,但對於@「看起來不像字符串值,這是一個數字。」字符串都可以。
[attributedString boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin].size
或
NSRange glyphRange = [layoutManager glyphRangeForTextContainer:textContainer];
NSSize textSize = [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer].size;
任何人都可以解釋我爲什麼一些字符串我收到錯誤的大小:當我收到字符串大小
所有同樣的情況?
謝謝。
是的,謝謝!該標籤將其內容略微插入。 – Lexandr