首页 > 代码库 > 计算string高度
计算string高度
一、CTFramesetterSuggestFrameSizeWithConstraints计算文本显示所占区域修正方法
UIFont *uiFont = [UIFont fontWithName:@"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 enough to 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 spacing attributes over the span
CFAttributedStringSetAttribute(string, textRange, kCTFontAttributeName, ctFont);
CFAttributedStringSetAttribute(string, textRange, kCTParagraphStyleAttributeName, paragraphStyle);
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(string);
CFRange range;
CGSize sizeAfterRender = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, textRange, nil,
CGSizeMake(300, 1000000)
, &range);
二、ios7.0以上方法
NSDictionary
*attributes = @{
NSFontAttributeName
:font};
CGSize lablesize = [showtext boundingRectWithSize:CGSizeMake(300,1000000) options:
NSStringDrawingUsesLineFragmentOrigin
|
NSStringDrawingUsesFontLeading
attributes:attributes
context:
nil
].size;
计算string高度
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。