nsa*_*ion 8 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);
Run Code Online (Sandbox Code Playgroud)
返回的大小始终具有正确的宽度计算,但高度始终略短于预期.
这是使用此方法的正确方法吗?
有没有其他方法来布局核心文本?
似乎我不是唯一遇到此方法问题的人.请参阅https://devforums.apple.com/message/181450.
编辑:我使用Quartz测量相同的字符串sizeWithFont:
,为属性字符串和Quartz提供相同的字体.以下是我收到的测量数据:
核心文字:133.569336 x 16.592285
石英:135.000000 x 31.000000
小智 14
试试这个..似乎工作:
+(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;
}
Run Code Online (Sandbox Code Playgroud)
对于单行框架,请尝试以下方法:
line = CTLineCreateWithAttributedString((CFAttributedStringRef) string);
CGFloat ascent;
CGFloat descent;
CGFloat width = CTLineGetTypographicBounds(line, &ascent, &descent, NULL);
CGFloat height = ascent+descent;
CGSize textSize = CGSizeMake(width,height);
Run Code Online (Sandbox Code Playgroud)
对于多线框架,您还需要添加线条的引线(请参阅" 核心文本编程指南"中的示例代码)
出于某种原因,CTFramesetterSuggestFrameSizeWithConstraints()
使用上升和下降的差异来计算高度:
CGFloat wrongHeight = ascent-descent;
CGSize textSize = CGSizeMake(width, wrongHeight);
Run Code Online (Sandbox Code Playgroud)
这可能是一个错误?
我的框架宽度还有其他一些问题; 它值得一试,因为它只在特殊情况下显示.有关更多信息,请参阅此问
归档时间: |
|
查看次数: |
11248 次 |
最近记录: |