在下面的代码中,CTFramesetterSuggestFrameSizeWithConstraints
有时会返回一个 CGSize
,其高度不足以包含传递到其中的所有文本。我确实看过this answer 。但就我而言,文本框的宽度需要保持不变。有没有其他/更好的方法来计算我的属性字符串的正确高度?谢谢!
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attributedString);
CGSize tmpSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0,0), NULL, CGSizeMake(self.view.bounds.size.width, CGFLOAT_MAX), NULL);
CGSize textBoxSize = CGSizeMake((int)tmpSize.width + 1, (int)tmpSize.height + 1);
最佳答案
CTFramesetterSuggestFrameSizeWithConstraints 工作正常。高度太短的原因是附加到属性字符串的默认段落样式中的前导。如果您没有将段落样式附加到字符串,则 CoreText 返回呈现文本所需的高度,但行之间没有空格。这花了我很长时间才弄清楚。文档中没有任何内容说明这一点。我只是碰巧注意到我的高度矮了等于(行数 x 预期行距)。要获得您期望的高度结果,您可以使用如下代码:
NSString *text = @"This\nis\nsome\nmulti-line\nsample\ntext."
UIFont *uiFont = [UIFont fontWithName:@"Helvetica" size:17.0];
CTFontRef ctFont = CTFontCreateWithName((CFStringRef) uiFont.fontName, uiFont.pointSize, NULL);
// When you create an attributed string the default paragraph style has a leading
// of 0.0. Create a paragraph style that will set the line adjustment equal to
// the leading value of the font.
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 fitRange;
CGSize frameSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, textRange, NULL, bounds, &fitRange);
CFRelease(framesetter);
CFRelease(string);
关于iphone - CTFramesetterSuggestFrameSizeWithConstraints 有时返回不正确的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3374591/