getAttributedStringHeightWithString

来源:互联网 发布:小gps数据导不出 编辑:程序博客网 时间:2024/06/03 08:59
  1. - (int)getAttributedStringHeightWithString:(NSAttributedString *)  string  WidthValue:(int) width  
  2. {  
  3.    int total_height = 0;  
  4.      
  5.    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)string);    //string 为要计算高度的NSAttributedString  
  6.    CGRect drawingRect = CGRectMake(0, 0, width, 1000);  //这里的高要设置足够大  
  7.    CGMutablePathRef path = CGPathCreateMutable();  
  8.    CGPathAddRect(path, NULL, drawingRect);  
  9.    CTFrameRef textFrame = CTFramesetterCreateFrame(framesetter,CFRangeMake(0,0), path, NULL);  
  10.    CGPathRelease(path);  
  11.    CFRelease(framesetter);  
  12.      
  13.    NSArray *linesArray = (NSArray *) CTFrameGetLines(textFrame);  
  14.      
  15.    CGPoint origins[[linesArray count]];  
  16.    CTFrameGetLineOrigins(textFrame, CFRangeMake(0, 0), origins);  
  17.      
  18.    int line_y = (int) origins[[linesArray count] -1].y;  //最后一行line的原点y坐标  
  19.      
  20.    CGFloat ascent;  
  21.    CGFloat descent;  
  22.    CGFloat leading;  
  23.      
  24.    CTLineRef line = (CTLineRef) [linesArray objectAtIndex:[linesArray count]-1];  
  25.    CTLineGetTypographicBounds(line, &ascent, &descent, &leading);  
  26.      
  27.    total_height = 1000 - line_y + (int) descent +1;    //+1为了纠正descent转换成int小数点后舍去的值  
  28.      
  29.    CFRelease(textFrame);  
  30.      
  31.    return total_height;  
  32.      
  33. }  

0 0
原创粉丝点击