(zhuan zi) http://blog.sina.com.cn/s/blog_6308b98c0101byh9.html
[iOS]CTFramesetterSuggestFrameSizeWithConstraints计算文本显示所占区域修正方法
(2012-12-19 15:48:45)标签: 杂谈 |
iOS中使用CTFramesetterSuggestFram
eSizeWithConstraints来计算文本显示所占区域大小,计算的区域有一定的误差,有人反应这个是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] = {kCTParagraphStyleSpecifi
erLineSpacingAdjustment, sizeof (CGFloat),&leading };
CTParagraphStyleRef
paragraphStyle =CTParagraphStyleCreate(paragraphSettings, 1);
CFRange textRange = CFRangeMake(0, text.length);
//
Create an empty mutable string big enoughto hold our test
CFMutableAttributedStrin
gRef string =CFAttributedStringCreate
Mutable(kCFAllocatorDefault,text.length);
//
Inject our text into it
CFAttributedStringReplac
eString(string, CFRangeMake(0, 0),(CFStringRef) text);
//
Apply our font and line spacingattributes over the span
CFAttributedStringSetAtt
ribute(string, textRange,kCTFontAttributeName, ctFont);
CFAttributedStringSetAtt
ribute(string, textRange,kCTParagraphStyleAttribu
teName, paragraphStyle);
CTFramesetterRef framesetter =CTFramesetterCreateWithA
ttributedString(string);
这段代码中,最主要的是对CTFramesetterRef的
framesetter进行设置,设置
framesetter之后,就可以通过
CTFramesetterSuggestFram eSizeWithConstraints来计算文字所占区域大小了。

本文介绍了一种修正iOS中CTFramesetterSuggestFrameSizeWithConstraints计算文本显示区域大小的方法,该方法存在一定的误差,可能未正确计算行间距。通过设置字体、行间距等属性,并利用CTFramesetterRef进行调整,可以提高文本布局计算的准确性。

被折叠的 条评论
为什么被折叠?



