- (int)getAttributedStringHeightWithString:(NSAttributedString *) string WidthValue:(int) width
{
int total_height = ; CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)string); //string 为要计算高度的NSAttributedString
CGRect drawingRect = CGRectMake(, , width, ); //这里的高要设置足够大
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, drawingRect);
CTFrameRef textFrame = CTFramesetterCreateFrame(framesetter,CFRangeMake(,), path, NULL);
CGPathRelease(path);
CFRelease(framesetter); NSArray *linesArray = (NSArray *) CTFrameGetLines(textFrame); CGPoint origins[[linesArray count]];
CTFrameGetLineOrigins(textFrame, CFRangeMake(, ), origins); int line_y = (int) origins[[linesArray count] -].y; //最后一行line的原点y坐标 CGFloat ascent;
CGFloat descent;
CGFloat leading; CTLineRef line = (CTLineRef) [linesArray objectAtIndex:[linesArray count]-];
CTLineGetTypographicBounds(line, &ascent, &descent, &leading); total_height = - line_y + (int) descent +; //+1为了纠正descent转换成int小数点后舍去的值 CFRelease(textFrame); return total_height; }
来自:http://blog.csdn.net/iunion/article/details/7925951