Fork me on GitHub

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

 
- (CGSize) measureFrame: (CTFrameRef) frame forContext: (CGContext *) cgContext
{//frame为排版后的文本
CGPathRefframePath =CTFrameGetPath(frame);
CGRectframeRect =CGPathGetBoundingBox(framePath);
 
CFArrayReflines =CTFrameGetLines(frame);
CFIndexnumLines =CFArrayGetCount(lines);
 
CGFloatmaxWidth =0;
CGFloattextHeight =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.
CFIndexlastLineIndex = numLines -1;
for(CFIndexindex =0; index < numLines; index++)
{
CGFloatascent, descent, leading, width;
CTLineRefline = (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.
CGPointlastLineOrigin;
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.
returnCGSizeMake(ceil(maxWidth),ceil(textHeight));
}

posted on 2012-02-08 19:30  pengyingh  阅读(2792)  评论(0编辑  收藏  举报

导航