本文主要的內容是討論如何使用CoreText進行最簡單的文本內容的繪制,同時也談到的CoreText繪圖的一個最基本但是也是最重要的CoreText坐標系的概念,CoreText坐標系的概念是貫穿所有的CoreText繪圖場景,所有這里先做個介紹
其它文章:
CoreText入門(一)-文本繪制
CoreText入門(二)-繪制圖片
CoreText進階(三)-事件處理
CoreText進階(四)-文字行數限制和顯示更多
CoreText進階(五)- 文字排版樣式和效果
CoreText進階(六)-內容大小計算和自動布局
CoreText進階(七)-添加自定義View和對其
本文的主要內容如下
- CoreText是什么
- 坐標系
- 簡單的文字繪制
- 總結
Demo:CoreTextDemo
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入門(二)-繪制圖片會涉及到CoreText中更多的概念