IOS core text计算文本高度及最大宽度


 
- ( CGSize ) measureFrame: ( CTFrameRef ) frame forContext: (CGContext *) cgContext
{//frame为排版后的文本
CGPathRef framePath = CTFrameGetPath (frame);
CGRect frameRect = CGPathGetBoundingBox (framePath);

CFArrayRef lines = CTFrameGetLines (frame);
CFIndex numLines = CFArrayGetCount (lines);

CGFloat maxWidth = 0 ;
CGFloat textHeight = 0 ;

// Now run through each line determining the maximum width of all the lines.
// We special case the last line of text. While we've got it's descent handy,
// we'll use it to calculate the typographic height of the text as well.
CFIndex lastLineIndex = numLines - 1 ;
for ( CFIndex index = 0 ; index < numLines; index++)
{
CGFloat ascent, descent, leading, width;
CTLineRef line = ( CTLineRef ) CFArrayGetValueAtIndex (lines, index);
width = CTLineGetTypographicBounds (line, &ascent,  &descent, &leading);

if (width > maxWidth)
{
maxWidth = width;
}

if (index == lastLineIndex)
{
// Get the origin of the last line. We add the descent to this
// (below) to get the bottom edge of the last line of text.
CGPoint lastLineOrigin;
CTFrameGetLineOrigins (frame, CFRangeMake (lastLineIndex, 1 ), &lastLineOrigin);

// The height needed to draw the text is from the bottom of the last line
// to the top of the frame.
textHeight =  CGRectGetMaxY (frameRect) - lastLineOrigin. y + descent;
}
}

// For some text the exact typographic bounds is a fraction of a point too
// small to fit the text when it is put into a context. We go ahead and round
// the returned drawing area up to the nearest point.  This takes care of the
// discrepencies.
return CGSizeMake ( ceil (maxWidth), ceil (textHeight));
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值