前言:今天介绍绘制文本的流程和需要要到 CoreText 中的类库。
绘制流程
1、使用 UIGraphicsGetCurrentContext() 获取上下文;
CGContextRef context = UIGraphicsGetCurrentContext();
2、翻转坐标系
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
3、创建需要绘制的文本(NSAttributedString)
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:@"\tWhen I will learn CoreText, i think it will hard for me. But it is easy.\n\tIn fact,if you bengin learn, you can know that every thing is easy when you start.you just need some knowlages"];
// 使用 - (void)addAttribute:(NSAttributedStringKey)name value:(id)value range:(NSRange)range; 给富文本添加属性
4、根据 NSAttributedString 创建 CTFramesetterRef
CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attString);
5、创建绘制区域 (CGPathRef)
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(0.0, self.bounds.size.height + 100, 100.0, 100.0));
6、根据 CTFramesetterRef 和 CGPathRef 创建 CTFrame
CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, [attString length]), path, NULL);
7、使用 CTFrameDraw 在上下文上绘制
CTFrameDraw(frame, context);
CoreText 中使用到的类库
CFAttributedStringRef:属性字符串,用于存储需要绘制文本的字符和字符属性。
CTFramesetterRef:根据属性字符串对象和形状描述对象进行创建一个可以图形对象。