您的位置:首页 > 移动开发 > IOS开发

[iOS]CTFramesetterSuggestFrameSizeWithConstraints计算文本显示所占区域修正方法

2013-05-14 21:44 1606 查看

(zhuan zi) http://blog.sina.com.cn/s/blog_6308b98c0101byh9.html

[iOS]CTFramesetterSuggestFrameSizeWithConstraints计算文本显示所占区域修正方法

(2012-12-19 15:48:45)


转载▼

标签:

杂谈

iOS中使用CTFramesetterSuggestFrameSizeWithConstraints来计算文本显示所占区域大小,计算的区域有一定的误差,有人反应这个是sdk中的bug导致,个人发现可能是没有将行间距计算进去,所以会导致这种问题,导致没有将行间距计算进去的原因有可能是设置的文字属性的方式问题,为了修正这个问题,可以尝试用下面的代码:

UIFont *uiFont = [UIFontfontWithName:@"Helvetica" size:17.0];
CTFontRef ctFont = CTFontCreateWithName((CFStringRef)uiFont.fontName, uiFont.pointSize, NULL);

CGFloat leading = uiFont.lineHeight - uiFont.ascender +uiFont.descender;
CTParagraphStyleSetting paragraphSettings[1] = {kCTParagraphStyleSpecifierLineSpacingAdjustment, sizeof (CGFloat),&leading };

CTParagraphStyleRef paragraphStyle =CTParagraphStyleCreate(paragraphSettings, 1);
CFRange textRange = CFRangeMake(0, text.length);

// Create an empty mutable string big enoughto hold our test
CFMutableAttributedStringRef string =CFAttributedStringCreateMutable(kCFAllocatorDefault,text.length);

// Inject our text into it
CFAttributedStringReplaceString(string, CFRangeMake(0, 0),(CFStringRef) text);

// Apply our font and line spacingattributes over the span
CFAttributedStringSetAttribute(string, textRange,kCTFontAttributeName, ctFont);
CFAttributedStringSetAttribute(string, textRange,kCTParagraphStyleAttributeName, paragraphStyle);

CTFramesetterRef framesetter =CTFramesetterCreateWithAttributedString(string);

这段代码中,最主要的是对CTFramesetterRef的framesetter进行设置,设置framesetter之后,就可以通过CTFramesetterSuggestFrameSizeWithConstraints来计算文字所占区域大小了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: