zoukankan      html  css  js  c++  java
  • 30、准确计算CoreText高度的方法

    http://ios-iphone.diandian.com/post/2012-03-29/18389515

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

    //关于line坐标位置y为下图黑线所在位置 descent为黑线下部分字体的高度

    //关于字体各部分高度说明  http://ios-iphone.diandian.com/post/2012-03-29/18055023  

  • 相关阅读:
    OpenGL编程 基础篇(二)Sierpinski垫片
    PAT1045. Favorite Color Stripe
    OpenGL编程 基础篇(一)
    百练1145:Tree Summing
    百练1745:Divisibility
    百练1321:棋盘问题
    Scrapy架构及其组件之间的交互
    MongoDB快速入门
    Redis快速入门
    Memcache所有方法及参数详解
  • 原文地址:https://www.cnblogs.com/xuejinhui/p/4768342.html
Copyright © 2011-2022 走看看