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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


html5中section的用法
span标签和p标签的区别
jsp文件和html文件的区别是什么
span标签和div的区别
html颜色代码表大全
span标签的作用是什么
dhtml的主要组成部分包括什么
html编辑器哪个软件好用
span标签属于什么样式标签
html文件乱码怎么办
html怎么读取json文件
html文件打开乱码怎么恢复原状
html怎么链接外部css
html文件怎么保存到本地
html怎么链接css文件
html和css怎么连接
html和css怎么关联
html文件怎么保存到一个站点
html文件怎么写
html出现乱码怎么解决