版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012581760/article/details/82864182
步骤1:创建NSAttributedString
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:@"iOS程序在启动时会创建一个主线程,而在一个线程只能执行一件事情,如果在主线程执行某些耗时操作,例如加载网络图片,下载资源文件等会阻塞主线程(导致界面卡死,无法交互),所以就需要使用多线程技术来避免这类情况。iOS中有三种多线程技术 NSThread,NSOperation,GCD,这三种技术是随着IOS发展引入的,抽象层次由低到高,使用也越来越简单。"];
CGRect viewRect = CGRectMake(0, 0, [UIScreen mainScreen].bounds.width, rectSize.height); //CGRectGetHeight(self.bounds)
步骤2:创建绘制区域CGPathRef
//创建一个用来描画文字的路径,其区域为当前视图的bounds CGPath
CGMutablePathRef pathRef = CGPathCreateMutable();
CGPathAddRect(pathRef, NULL, viewRect);
步骤3:根据CTFramesetterRef和CGPathRef创建CTFrame
CTFramesetterRef framesetterRef = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attString);
//创建由framesetter管理的frame,是描画文字的一个视图范围 CTFrame
CTFrameRef frameRef = CTFramesetterCreateFrame(framesetterRef, CFRangeMake(0, 0), pathRef, nil);
CFArrayRef lines = CTFrameGetLines(frameRef);
获取有多少行
CFIndex lineCount = CFArrayGetCount(lines);
内存管理
CFRelease(pathRef);
CFRelease(frameRef);
CFRelease(framesetterRef);
// 自动获取行高
CGFloat frameHeight = 0;
frameHeight = lineCount*(styleModel.font.lineHeight+styleModel.lineSpace)+styleModel.lineSpace;