cocoa – Core Text的CTFramesetterSuggestFrameSizeWithConstraints()每次都返回不正确的大小

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

    CFIndex startIndex = 0;

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path,Box);

    // Create a frame for this column and draw it.
    CTFrameRef frame = CTFramesetterCreateFrame(framesetter,CFRangeMake(startIndex,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;
}

相关文章

Mip是什么意思以及作用有哪些
怎么测试Mip页面运行情况
MIP安装的具体步骤有哪些
HTML添加超链接、锚点的方法及作用详解(附视频)
MIP的规则有哪些
Mip轮播图组件中的重要属性讲解