zoukankan      html  css  js  c++  java
  • 如何精确计算文本所占的行数

    如何精确计算文本所占的行数

    在 iOS 开发过程中,需要计算一段文字所占的行数,试了几种方式都很难准确计算。

    通过coreText 框架,去精确计算一段文本所占的行数。

    - (NSArray *)getLinesArrayOfStringInLabel:(NSString *)string font:(UIFont *)font andLableWidth:(CGFloat)lableWidth{
        
        CTFontRef myFont = CTFontCreateWithName(( CFStringRef)([font fontName]), [font pointSize], NULL);
        NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:string];
        [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge  id)myFont range:NSMakeRange(0, attStr.length)];
        CFRelease(myFont);
        CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(( CFAttributedStringRef)attStr);
        CGMutablePathRef path = CGPathCreateMutable();
        CGPathAddRect(path, NULL, CGRectMake(0,0,lableWidth,100000));
        CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
        NSArray *lines = ( NSArray *)CTFrameGetLines(frame);
        NSMutableArray *linesArray = [[NSMutableArray alloc]init];
        for (id line in lines) {
            CTLineRef lineRef = (__bridge  CTLineRef )line;
            CFRange lineRange = CTLineGetStringRange(lineRef);
            NSRange range = NSMakeRange(lineRange.location, lineRange.length);
            NSString *lineString = [string substringWithRange:range];
            CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithFloat:0.0]));
            CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithInt:0.0]));
            [linesArray addObject:lineString];
        }
        
        CGPathRelease(path);
        CFRelease( frame );
        CFRelease(frameSetter);
        return (NSArray *)linesArray;
    }
    

    参考

  • 相关阅读:
    火狐浏览器修改userAgent
    清除linux缓存命令
    linux主机间复制文件
    解决两台centos虚拟机Telnet服务无法联机的问题
    Install Redis on CentOS 6.4--转
    解决 ERROR: JDWP Transport dt_socket failed to initialize, TRANSPORT_INIT(510)异常
    主机访问虚拟机中linux上的web服务
    How can I exclude directories from grep -R?
    RPM安装命令总结--转载
    centos mongodb安装及简单实例
  • 原文地址:https://www.cnblogs.com/miaocunfa/p/13181490.html
Copyright © 2011-2022 走看看