iphone - CTFramesetterSuggestFrameSizeWithConstraints 有时返回不正确的大小?

标签 iphone xcode core-graphics core-text

在下面的代码中,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/

相关文章:

iPhone 开发 : Get images from RSS feed

iphone - 应用内购买在生产应用中失败

ios - 使用 UIImageView+AFNetworking Xcode 7 加载图像

ios - 测试我的应用程序时没有显示任何内容

xcode - 从两个应用程序创建一个 "Universal Binary"?

iphone - iOS 5.1 应用程序与目标 iOS 5.1 一起运行 xcode 4.6.2,无法限制某些方向的 View ?

iphone - 如何在cocos2d for iphone中获取CCSprite的宽度和高度

ios - 是否有 CGPath 的替代方法允许计算给定位置的路径上的点?

ios - 当想要使用 UISlider 增加 View 大小时,CGAffineTransformRotate 设置为其初始状态

objective-c - 创建单色 CGImageRef(每像素位图 1 位)