本文主要的內(nèi)容是討論如何使用CoreText進(jìn)行最簡(jiǎn)單的文本內(nèi)容的繪制蔽豺,同時(shí)也談到的CoreText繪圖的一個(gè)最基本但是也是最重要的CoreText坐標(biāo)系的概念绑咱,CoreText坐標(biāo)系的概念是貫穿所有的CoreText繪圖場(chǎng)景,所有這里先做個(gè)介紹
其它文章:
CoreText入門(mén)(一)-文本繪制
CoreText入門(mén)(二)-繪制圖片
CoreText進(jìn)階(三)-事件處理
CoreText進(jìn)階(四)-文字行數(shù)限制和顯示更多
CoreText進(jìn)階(五)- 文字排版樣式和效果
CoreText進(jìn)階(六)-內(nèi)容大小計(jì)算和自動(dòng)布局
CoreText進(jìn)階(七)-添加自定義View和對(duì)其
本文的主要內(nèi)容如下
- CoreText是什么
- 坐標(biāo)系
- 簡(jiǎn)單的文字繪制
- 總結(jié)
Demo:CoreTextDemo
CoreText是什么
蘋(píng)果的文檔中對(duì)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.
翻譯過(guò)來(lái)的意思就是:CoreText是一種高級(jí)的底層技術(shù), 用于布局文本和處理字體乐横。CoreText直接與Core Graphics (CG) 一起工作, 也稱(chēng)為Quartz, 它是在 OS X 和 iOS 的最底層的處理二維成像的高速圖形渲染引擎垦页。
坐標(biāo)系
UIKit的坐標(biāo)系原點(diǎn)是在右上角赋续,CoreText的坐標(biāo)原點(diǎn)是在左下角,并且繪制的內(nèi)容是顛倒的,所以需要進(jìn)行坐標(biāo)轉(zhuǎn)換囊陡,繪制的內(nèi)容顯示才能正常
使用以下的代碼進(jìn)行坐標(biāo)系的轉(zhuǎn)換
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1, -1);
步驟示例圖:
簡(jiǎn)單的文字繪制
效果圖
文字繪制的流程圖:
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1, -1);
// 繪制區(qū)域
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, self.bounds);
// 繪制的內(nèi)容屬性字符串
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創(chuàng)建CTFrame
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attrStr);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attrStr.length), path, NULL);
// 使用CTFrame在CGContextRef上下文上繪制
CTFrameDraw(frame, context);
}
總結(jié)
使用CoreText繪制文本步驟比較簡(jiǎn)單芳绩,這里面子用到CoreText中的一個(gè)類(lèi)CTFrame
,CoreText中還有許多其他的概念沒(méi)有涉及到撞反,下一篇CoreText入門(mén)(二)-繪制圖片會(huì)涉及到CoreText中更多的概念