转自:http://lists.apple.com/archives/quartz-dev/2008/Mar/msg00079.html
- (
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));
}
|