一、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;