本文主要的内容是讨论如何使用CoreText进行最简单的文本内容的绘制,同时也谈到的CoreText绘图的一个最基本但是也是最重要的CoreText坐标系的概念,CoreText坐标系的概念是贯穿所有的CoreText绘图场景,所有这里先做个介绍
其它文章:
本文的主要内容如下
- CoreText是什么
- 坐标系
- 简单的文字绘制
- 总结
Demo:
CoreText是什么
苹果的文档中对CoreText的描述如下
Core Text is an advanced, low-level technology for laying out text and handling fonts. Core Text works directly with Core Graphics (CG), also known as Quartz, which is the high-speed graphics rendering engine that handles two-dimensional imaging at the lowest level in OS X and iOS.
翻译过来的意思就是:CoreText是一种高级的底层技术, 用于布局文本和处理字体。CoreText直接与Core Graphics (CG) 一起工作, 也称为Quartz, 它是在 OS X 和 iOS 的最底层的处理二维成像的高速图形渲染引擎。
坐标系
UIKit的坐标系原点是在右上角,CoreText的坐标原点是在左下角,并且绘制的内容是颠倒的,所以需要进行坐标转换,绘制的内容显示才能正常
 使用以下的代码进行坐标系的转换CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetTextMatrix(context, CGAffineTransformIdentity); CGContextTranslateCTM(context, 0, self.bounds.size.height); CGContextScaleCTM(context, 1, -1);
步骤示例图:
简单的文字绘制
效果图

文字绘制的流程图:
- (void)drawRect:(CGRect)rect { [super drawRect:rect]; CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetTextMatrix(context, CGAffineTransformIdentity); CGContextTranslateCTM(context, 0, self.bounds.size.height); CGContextScaleCTM(context, 1, -1); // 绘制区域 CGMutablePathRef path = CGPathCreateMutable(); CGPathAddRect(path, NULL, self.bounds); // 绘制的内容属性字符串 NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:18], NSForegroundColorAttributeName: [UIColor blueColor] }; NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@"Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world" attributes:attributes]; // 使用NSMutableAttributedString创建CTFrame CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attrStr); CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attrStr.length), path, NULL); // 使用CTFrame在CGContextRef上下文上绘制 CTFrameDraw(frame, context);}
总结
使用CoreText绘制文本步骤比较简单,这里面子用到CoreText中的一个类CTFrame
,CoreText中还有许多其他的概念没有涉及到,下一篇会涉及到CoreText中更多的概念