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

标签 cocoa cocoa-touch core-text

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

相关文章:

cocoa - 如何在设置其字符串值后居中对齐 NSTextField

cocoa - NSTableView 带有加号和减号按钮

objective-c - NSTextField 不会设置 StringValue

iphone - iPhone 应用程序存储数据的最佳实践

cocoa-touch - iPad:通过手指触摸屏幕来测量/检测覆盖区域(不仅仅是触摸坐标)

ios - 核心文本 - 如何知道文本是否从右到左

cocoa - 如何使用 cocoa 编程语言运行 .command 文件?

ios - 如何在iOS中的后台线程上绘制文本?

html - Core Text 渲染 HTML 内容

iPhone应用程序: How to fill an image with empty areas with coregraphics?