Core Text的CTFramesetterSuggestFrameSizeWithConstraints()每次返回不正确的大小 [英] Core Text's CTFramesetterSuggestFrameSizeWithConstraints() returns incorrect size everytime
问题描述
根据文档, CTFramesetterSuggestFrameSizeWithConstraints()
确定字符串范围所需的框架大小。
According to the docs, CTFramesetterSuggestFrameSizeWithConstraints ()
"determines the frame size needed for a string range".
不幸的是,这个函数返回的大小是不准确的。这是我在做什么:
Unfortunately the size returned by this function is never accurate. Here is what I am doing:
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);
返回的尺寸总是有正确的宽度计算,但是高度总是比预期的稍短。
The returned size always has the correct width calculated, however the height is always slightly shorter than what is expected.
这是使用此方法的正确方法吗?
Is this the correct way to use this method?
是否有其他方法来布局核心文本?
Is there any other way to layout Core Text?
似乎我不是唯一遇到这种方法问题的人。请参阅 https://devforums.apple.com/message/181450 。
Seems I am not the only one to run into problems with this method. See https://devforums.apple.com/message/181450.
编辑:
我使用 sizeWithFont:
测量与Quartz相同的字符串,为属性字符串,和石英。这是我收到的测量:
I measured the same string with Quartz using sizeWithFont:
, supplying the same font to both the attributed string, and to Quartz. Here are the measurements I received:
核心文字:133.569336 x 16.592285
Core Text: 133.569336 x 16.592285
Quartz:135.000000 x 31.000000
Quartz: 135.000000 x 31.000000
推荐答案
try this.. seem to work:
+(CGFloat)heightForAttributedString:(NSAttributedString *)attrString forWidth:(CGFloat)inWidth
{
CGFloat H = 0;
// Create the framesetter with the attributed string.
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString( (CFMutableAttributedStringRef) attrString);
CGRect box = CGRectMake(0,0, inWidth, CGFLOAT_MAX);
CFIndex startIndex = 0;
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, box);
// Create a frame for this column and draw it.
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(startIndex, 0), path, NULL);
// Start the next frame at the first character not visible in this frame.
//CFRange frameRange = CTFrameGetVisibleStringRange(frame);
//startIndex += frameRange.length;
CFArrayRef lineArray = CTFrameGetLines(frame);
CFIndex j = 0, lineCount = CFArrayGetCount(lineArray);
CGFloat h, ascent, descent, leading;
for (j=0; j < lineCount; j++)
{
CTLineRef currentLine = (CTLineRef)CFArrayGetValueAtIndex(lineArray, j);
CTLineGetTypographicBounds(currentLine, &ascent, &descent, &leading);
h = ascent + descent + leading;
NSLog(@"%f", h);
H+=h;
}
CFRelease(frame);
CFRelease(path);
CFRelease(framesetter);
return H;
}
这篇关于Core Text的CTFramesetterSuggestFrameSizeWithConstraints()每次返回不正确的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!