在下面的代码中,CTFramesetterSuggestFrameSizeWithConstraints有时返回一个CGSize高度不足以包含传递给它的所有文本的高度.我确实看过这个答案.但在我的情况下,文本框的宽度需要是恒定的.有没有其他/更好的方法来确定我的属性字符串的正确高度?谢谢!
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);
Run Code Online (Sandbox Code Playgroud) 根据文档,CTFramesetterSuggestFrameSizeWithConstraints ()"确定字符串范围所需的帧大小".
不幸的是,这个函数返回的大小永远不准确.这是我在做的事情:
NSAttributedString *string = [[[NSAttributedString alloc] initWithString:@"lorem ipsum" attributes:nil] autorelease];
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef) string);
CGSize textSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0,0), NULL, CGSizeMake(rect.size.width, CGFLOAT_MAX), NULL);
Run Code Online (Sandbox Code Playgroud)
返回的大小始终具有正确的宽度计算,但高度始终略短于预期.
这是使用此方法的正确方法吗?
有没有其他方法来布局核心文本?
似乎我不是唯一遇到此方法问题的人.请参阅https://devforums.apple.com/message/181450.
编辑:我使用Quartz测量相同的字符串sizeWithFont:,为属性字符串和Quartz提供相同的字体.以下是我收到的测量数据:
核心文字:133.569336 x 16.592285
石英:135.000000 x 31.000000