本文主要的内容是讨论如何使用CoreText进行最简单的文本内容的绘制,同时也谈到的CoreText绘图的一个最基本可是也是最重要的CoreText坐标系的概念,CoreText坐标系的概念是贯穿全部的CoreText绘图场景,全部这里先作个介绍git
其它文章:
CoreText入门(一)-文本绘制
CoreText入门(二)-绘制图片
CoreText进阶(三)-事件处理
CoreText进阶(四)-文字行数限制和显示更多
CoreText进阶(五)- 文字排版样式和效果
CoreText进阶(六)-内容大小计算和自动布局
CoreText进阶(七)-添加自定义View和对其布局
本文的主要内容以下字体
Demo:CoreTextDemo.net
苹果的文档中对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.3d
翻译过来的意思就是:CoreText是一种高级的底层技术, 用于布局文本和处理字体。CoreText直接与Core Graphics (CG) 一块儿工做, 也称为Quartz, 它是在 OS X 和 iOS 的最底层的处理二维成像的高速图形渲染引擎。code
UIKit的坐标系原点是在右上角,CoreText的坐标原点是在左下角,而且绘制的内容是颠倒的,因此须要进行坐标转换,绘制的内容显示才能正常orm
 使用如下的代码进行坐标系的转换blog
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入门(二)-绘制图片会涉及到CoreText中更多的概念