gpt4 book ai didi

cocoa - Core Text 的 CTFramesetterSuggestFrameSizeWithConstraints() 每次都会返回错误的大小

转载 作者:行者123 更新时间:2023-12-03 16:05:02 24 4
gpt4 key购买 nike

根据文档,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);

返回的尺寸始终具有计算出的正确宽度,但高度始终比预期稍短。

这是使用此方法的正确方法吗?

还有其他方法来布局核心文本吗?

似乎我不是唯一一个使用此方法遇到问题的人。请参阅https://devforums.apple.com/message/181450 .

编辑:我使用 sizeWithFont: 使用 Quartz 测量了相同的字符串,为属性字符串和 Quartz 提供相同的字体。以下是我收到的测量结果:

Core Text: 133.569336 x 16.592285

Quartz: 135.000000 x 31.000000

最佳答案

试试这个..似乎有效:

+(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;
}

关于cocoa - Core Text 的 CTFramesetterSuggestFrameSizeWithConstraints() 每次都会返回错误的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2707710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com