您的位置:首页 > 其它

boundingRectWithSize for NSAttributedString returning wrong size

2015-07-07 10:18 148 查看
https://stackoverflow.com/questions/13621084/boundingrectwithsize-for-nsattributedstring-returning-wrong-size

有个哥们儿的coretext方法非常好,解决了我的这个问题

@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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: