# boundingRectWithSize for NSAttributedString returning wrong size

472人阅读 评论(0)

https://stackoverflow.com/questions/13621084/boundingrectwithsize-for-nsattributedstring-returning-wrong-size

@warrenm ：

That method seems buggy in numerous ways. For one, as you note, it doesn't respect width constraints. For another, I've seen it crash because it seems to assume that all attributes are of NSObject type (for example, it tried to pass _isDefaultFace to a CTFontRef). It will also crash sometimes when a string drawing context is provided because it tries to add a nil-valued attribute to a mutable attributed string behind the scenes.

I would encourage you to avoid this method entirely. You can use Core Text directly to estimate the string size, if you can handle the overhead of creating a framesetter for each string you need to draw. It doesn't precisely honor width constraints either, but it seems to get within a few pixels, in my experience.

CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attrString);
CGSize targetSize = CGSizeMake(320, CGFLOAT_MAX);
CGSize fitSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, [attrString length]), NULL, targetSize, NULL);
CFRelease(framesetter);

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：12896次
• 积分：281
• 等级：
• 排名：千里之外
• 原创：15篇
• 转载：1篇
• 译文：0篇
• 评论：1条
文章分类
最新评论