美文网首页学习中ing...
计算UITextField、UItextView的高度

计算UITextField、UItextView的高度

作者: 那片阳光已醉 | 来源:发表于2017-01-16 17:55 被阅读9次
    - (int)getAttributedStringHeightWidthValue:(int)width byAtt:(NSMutableAttributedString *)attributedString
    {
        
        
        int total_height = 0;
        
        CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributedString);    //string 为要计算高度的NSAttributedString
        CGRect drawingRect = CGRectMake(0, 0, width, 100000);  //这里的高要设置足够大
        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坐标
        CGSize size[[linesArray count]];
        int line_height=(int) size[[linesArray count]-1].height;
        
        CGFloat ascent;
        CGFloat descent;
        CGFloat leading;
        
        CTLineRef line = (__bridge CTLineRef) [linesArray objectAtIndex:[linesArray count]-1];
        CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
        
        total_height = 100000 + line_height - line_y + (int) descent +1;//+1为了纠正descent转换成int小数点后舍去的值
        
        CFRelease(textFrame);
        
        return total_height;
        
    }
    
    
    

    相关文章

      网友评论

        本文标题:计算UITextField、UItextView的高度

        本文链接:https://www.haomeiwen.com/subject/rnepbttx.html