【API使用系列】Core Text专题

API接口文档

https://developer.apple.com/library/mac/#documentation/Carbon/Reference/CoreText_Framework_Ref/_index.html


1 CoreText.framework简介

1.1 常用类库

CoreText 框架中最常用的几个类:

CTFont

CTFontCollection

CTFontDescriptor

CTFrame

CTFramesetter

CTGlyphInfo

CTLine

CTParagraphStyle

CTRun

10 CTTextTab

11 CTTypesetter

1.1.1 CTFrame整体视窗组合图

先来了解一下该框架的整体视窗组合图:

【API使用系列】Core Text专题

    CTFrame 作为一个整体的画布(Canvas),其中由行(CTLine)组成,而每行可以分为一个或多个小方块(CTRun)。

    注意:你不需要自己创建CTRun,Core Text将根据NSAttributedString的属性来自动创建CTRun。每个CTRun对象对应不同的属性,正因此,你可以*的控制字体、颜色、字间距等等信息。

    通常处理步聚:

    1.使用core text就是先有一个要显示的string,然后定义这个string每个部分的样式->attributedString -> 生成 CTFramesetter -> 得到CTFrame -> 绘制(CTFrameDraw)

其中可以更详细的设置换行方式,对齐方式,绘制区域的大小等。

    2.绘制只是显示,点击事件就需要一个个判断了。

    CTFrame 包含了多个CTLine,并且可以得到各个line的真实位置与大小。判断点击处在不在某个line上。CTLine 又可以判断这个点(相对于ctline的坐标)处的文字范围。然后遍历这个string的所有NSTextCheckingResult,根据result的rang判断点击处在不在这个rang上,从而得到点击的链接与位置。

1.1.2 字体的基本知识

    字体(Font):是一系列字号、样式和磅值相同的字符(例如:10磅黑体Palatino)。现多被视为字样的同义词。

    字面(Face):是所有字号的磅值和格式的综合。

    字体集(Font family):是一组相关字体(例如:Franklin family包括Franklin Gothic、Fran-klinHeavy和FranklinCompressed)。

    磅值(Weight):用于描述字体粗度。典型的磅值,从最粗到最细,有极细、细、book、中等、半粗、粗、较粗、极粗。

    样式(Style):字形有三种形式:Roman type是直体;oblique type是斜体;utakuc type是斜体兼曲线(比Roman type更像书法体)。

    x高度(X height):指小写字母的平均高度(以x为基准)。磅值相同的两字母,x高度越大的字母看起来比x高度小的字母要大。

    Cap高度(Cap height):与x高度相似。指大写字母的平均高度(以C为基准)。

    下行字母(Descender):例如在字母q中,基线以下的字母部分叫下伸部分。

    上行字母(Ascender):x高度以上的部分(比如字母b)叫做上伸部分。

    基线(Baseline):通常在x、v、b、m下的那条线。

    描边(Stroke):组成字符的线或曲线。可以加粗或改变字符形状。

    衬线(Serif):用来使字符更可视的一条水平线。如字母左上角和下部的水平线。

    无衬线(Sans Serif):可以让排字员不使用衬线装饰。

    方形字(Block):这种字体的笔画使字符看起来比无衬线字更显眼,但还不到常见的衬线字的程度。例如Lubalin Graph就是方形字,这种字看起来好像是木头块刻的一样。

    手写体脚本(Calligraphic script):是一种仿效手写体的字体,例如Murray Hill或者Fraktur字体。

    艺术字(Decorative):像绘画般的字体。

    Pi符号(Pisymbol):非标准的字母数字字符的特殊符号,例如Wingdings和MathematicalPi。

    连写(Ligature):是一系列连写字母如fi、fl、ffi或ffl。由于字些字母形状的原因经常被连写,故排字员已习惯将它们连写。

【API使用系列】Core Text专题


1.1.3 字符属性名称

const CFStringRef kCTCharacterShapeAttributeName;

//字体形状属性  必须是CFNumberRef对象默认为0,非0则对应相应的字符形状定义,如1表示传统字符形状

const CFStringRef kCTFontAttributeName;

//字体属性   必须是CTFont对象

const CFStringRef kCTKernAttributeName;

//字符间隔属性 必须是CFNumberRef对象

const CFStringRef kCTLigatureAttributeName;

//设置是否使用连字属性,设置为0,表示不使用连字属性。标准的英文连字有FI,FL.默认值为1,既是使用标准连字。也就是当搜索到f时候,会把fl当成一个文字。必须是CFNumberRef 默认为1,可取0,1,2

const CFStringRefkCTForegroundColorAttributeName;

//字体颜色属性  必须是CGColor对象,默认为black

const CFStringRef kCTForegroundColorFromContextAttributeName;

 //上下文的字体颜色属性 必须为CFBooleanRef 默认为False,

const CFStringRef kCTParagraphStyleAttributeName;

//段落样式属性 必须是CTParagraphStyle对象 默认为NIL

const CFStringRefkCTStrokeWidthAttributeName;

//笔画线条宽度 必须是CFNumberRef对象,默为0.0f,标准为3.0f

const CFStringRefkCTStrokeColorAttributeName;

//笔画的颜色属性 必须是CGColorRef 对象,默认为前景色

const CFStringRefkCTSuperscriptAttributeName;

//设置字体的上下标属性 必须是CFNumberRef对象 默认为0,可为-1为下标,1为上标,需要字体支持才行。如排列组合的样式Cn1

const CFStringRefkCTUnderlineColorAttributeName;

//字体下划线颜色属性 必须是CGColorRef对象,默认为前景色

const CFStringRef kCTUnderlineStyleAttributeName;

//字体下划线样式属性 必须是CFNumberRef对象,默为kCTUnderlineStyleNone 可以通过CTUnderlineStypleModifiers 进行修改下划线风格

const CFStringRefkCTVerticalFormsAttributeName;

//文字的字形方向属性 必须是CFBooleanRef 默认为false,false表示水平方向,true表示竖直方向

const CFStringRef kCTGlyphInfoAttributeName;

//字体信息属性 必须是CTGlyphInfo对象

const CFStringRefkCTRunDelegateAttributeName

//CTRun 委托属性 必须是CTRunDelegate对象


1.2 段落样式CTParagraphStyle

1.2.1 段落样式定义

kCTParagraphStyleSpecifierAlignment = 0,                 //对齐属性

 kCTParagraphStyleSpecifierFirstLineHeadIndent = 1,       //首行缩进

 kCTParagraphStyleSpecifierHeadIndent = 2,                //段头缩进

 kCTParagraphStyleSpecifierTailIndent = 3,                //段尾缩进

 kCTParagraphStyleSpecifierTabStops = 4,                  //制表符模式

 kCTParagraphStyleSpecifierDefaultTabInterval = 5,        //默认tab间隔

 kCTParagraphStyleSpecifierLineBreakMode = 6,             //换行模式

 kCTParagraphStyleSpecifierLineHeightMultiple = 7,        //多行高

 kCTParagraphStyleSpecifierMaximumLineHeight = 8,         //最大行高

 kCTParagraphStyleSpecifierMinimumLineHeight = 9,         //最小行高

 kCTParagraphStyleSpecifierLineSpacing = 10,              //行距 

 kCTParagraphStyleSpecifierParagraphSpacing = 11,         //段落间距  在段的未尾(Bottom)加上间隔,这个值为负数。

 kCTParagraphStyleSpecifierParagraphSpacingBefore = 12,   //段落前间距 在一个段落的前面加上间隔。TOP

 kCTParagraphStyleSpecifierBaseWritingDirection = 13,     //基本书写方向

 kCTParagraphStyleSpecifierMaximumLineSpacing = 14,       //最大行距

 kCTParagraphStyleSpecifierMinimumLineSpacing = 15,       //最小行距

 kCTParagraphStyleSpecifierLineSpacingAdjustment = 16,    //行距调整

kCTParagraphStyleSpecifierCount = 17,        // 


1.2.2 对齐属性kCTParagraphStyleSpecifierAlignment

kCTLeftTextAlignment = 0,                //左对齐

kCTRightTextAlignment = 1,               //右对齐

kCTCenterTextAlignment = 2,              //居中对齐

kCTJustifiedTextAlignment = 3,           //文本对齐

kCTNaturalTextAlignment = 4              //自然文本对齐

    段落默认样式为 kCTNaturalTextAlignment


对齐方式设置代码:

CTTextAlignment alignment = kCTJustifiedTextAlignment;

CTParagraphStyleSetting alignmentStyle;

alignmentStyle.spec = kCTParagraphStyleSpecifierAlignment;//指定为对齐属性

alignmentStyle.valueSize = sizeof(alignment);

alignmentStyle.value=&alignment; 


1.2.3 首行缩进属性kCTParagraphStyleSpecifierFirstLineHeadIndent

首行缩进代码:

//首行缩进

CGFloat fristlineindent = 24.0f;

CTParagraphStyleSetting fristline;

fristline.spec = kCTParagraphStyleSpecifierFirstLineHeadIndent;

fristline.value = &fristlineindent;

fristline.valueSize = sizeof(float); 


1.2.4 段头缩进kCTParagraphStyleSpecifierHeadIndent

段头缩进代码:

//段缩进

CGFloat headindent = 10.0f;

CTParagraphStyleSetting head;

head.spec = kCTParagraphStyleSpecifierHeadIndent;

head.value = &headindent;

head.valueSize = sizeof(float);  


1.2.5 段尾缩进kCTParagraphStyleSpecifierTailIndent

段尾缩进代码:

//段尾缩进

CGFloat tailindent = 50.0f;

CTParagraphStyleSetting tail;

tail.spec = kCTParagraphStyleSpecifierTailIndent;

tail.value = &tailindent;

tail.valueSize = sizeof(float); 


1.2.6 制表符kCTParagraphStyleSpecifierTabStops

制表符(tab)代码:

//tab

CTTextAlignment tabalignment = kCTJustifiedTextAlignment;

CTTextTabRef texttab = CTTextTabCreate(tabalignment, 24, NULL);

CTParagraphStyleSetting tab;

tab.spec = kCTParagraphStyleSpecifierTabStops;

tab.value = &texttab;

tab.valueSize = sizeof(CTTextTabRef); 


1.2.7 换行模式CTLineBreakMode

换行模式:

kCTLineBreakByWordWrapping = 0,        //出现在单词边界时起作用,如果该单词不在能在一行里显示时,整体换行。此为段的默认值。

kCTLineBreakByCharWrapping = 1,        //当一行中最后一个位置的大小不能容纳一个字符时,才进行换行。

kCTLineBreakByClipping = 2,            //超出画布边缘部份将被截除。

kCTLineBreakByTruncatingHead = 3,      //截除前面部份,只保留后面一行的数据。前部份以...代替。

kCTLineBreakByTruncatingTail = 4,      //截除后面部份,只保留前面一行的数据,后部份以...代替。

kCTLineBreakByTruncatingMiddle = 5     //在一行中显示段文字的前面和后面文字,中间文字使用...代替。


换行模式代码:

//换行模式

CTParagraphStyleSetting lineBreakMode;

   CTLineBreakMode lineBreak = kCTLineBreakByWordWrapping;//kCTLineBreakByCharWrapping;//换行模式

lineBreakMode.spec = kCTParagraphStyleSpecifierLineBreakMode;

lineBreakMode.value = &lineBreak;

lineBreakMode.valueSize = sizeof(CTLineBreakMode);  


1.2.8 多行高度设置kCTParagraphStyleSpecifierLineHeightMultiple

多行高设置代码:

//多行高

CGFloat MutiHeight = 10.0f;

CTParagraphStyleSetting Muti;

Muti.spec = kCTParagraphStyleSpecifierLineHeightMultiple;

Muti.value = &MutiHeight;

Muti.valueSize = sizeof(float);


1.2.9 最大行高设置kCTParagraphStyleSpecifierLineHeightMultiple

最大行高代码:

//最大行高

CGFloat MaxHeight = 5.0f;

CTParagraphStyleSetting Max;

Max.spec = kCTParagraphStyleSpecifierLineHeightMultiple;

Max.value = &MaxHeight;

Max.valueSize = sizeof(float); 


1.2.10 行距设置kCTParagraphStyleSpecifierLineSpacing

行距代码:

//行距 

CGFloat _linespace = 5.0f;

CTParagraphStyleSetting lineSpaceSetting;

lineSpaceSetting.spec = kCTParagraphStyleSpecifierLineSpacing;

lineSpaceSetting.value = &_linespace;

lineSpaceSetting.valueSize = sizeof(float);


1.2.11 段前间距设置kCTParagraphStyleSpecifierLineSpacing

段前间距设置代码(段与段之间):

//段前间隔

CGFloat paragraphspace = 5.0f;

CTParagraphStyleSetting paragraph;

paragraph.spec = kCTParagraphStyleSpecifierLineSpacing;

paragraph.value = graphspace;

paragraph.valueSize = sizeof(float); 


1.2.12 基本书写方向kCTParagraphStyleSpecifierBaseWritingDirection

基本书写方向代码:

//书写方向

CTWritingDirection wd = kCTWritingDirectionRightToLeft;

CTParagraphStyleSetting writedic;

writedic.spec = kCTParagraphStyleSpecifierBaseWritingDirection;

writedic.value = &wd;

writedic.valueSize = sizeof(CTWritingDirection);  


1.3 使用举例

1.3.1 示例

//段落样式

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

//行间距

paragraphStyle.lineSpacing = 10.0;

//段落间距

//    paragraphStyle.paragraphSpacing = 20.0;

//    paragraphStyle.baseWritingDirection =NSWritingDirectionLeftToRight;

//    paragraphStyle.firstLineHeadIndent = 10.0;

//    paragraphStyle.headIndent = 50.0;

//    paragraphStyle.tailIndent = 200.0;

[supportAttributeStraddAttribute:NSParagraphStyleAttributeName value: paragraphStylerange: NSMakeRange(0, supportAttributeStr.length)];


如下代码不行:

//            CGFloat _linespace = 5.0f;

//            CTParagraphStyleSettinglineSpaceSetting;

//            lineSpaceSetting.spec =kCTParagraphStyleSpecifierLineSpacing;

//            lineSpaceSetting.value =&_linespace;

//            lineSpaceSetting.valueSize =sizeof(float);     

//            CTParagraphStyleSetting settings[]= {lineSpaceSetting};

//            CTParagraphStyleRef paragraphStyle= CTParagraphStyleCreate(settings, 1);  //第二个参数为settings的长度

//            NSMutableDictionary *attributes =[NSMutableDictionary dictionaryWithObject:(id)paragraphStyle forKey:(__bridgeNSString *)kCTParagraphStyleAttributeName];

//            [supportAttributeStraddAttributes:attributes range:NSMakeRange(0, supportAttributeStr.length)];

//            NSAttributedString*attributedString = [[NSAttributedString alloc] initWithData:[_htmlDatadataUsingEncoding:NSUnicodeStringEncoding]options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nilerror:nil];


1.3.2 此示例貌似不行

NSMutableAttributedString *mabstring = [[NSMutableAttributedString alloc]initWithString:@"This is a test of characterAttribute. 中文字符"];

【API使用系列】Core Text专题


//设置字体属性

CTFontRef font = CTFontCreateWithName(CFSTR("Georgia"), 40, NULL);

[mabstring addAttribute:(id)kCTFontAttributeName value:(id)font range:NSMakeRange(0, 4)];

【API使用系列】Core Text专题

//设置斜体字

CTFontRef font = CTFontCreateWithName((CFStringRef)[UIFont italicSystemFontOfSize:20].fontName, 14, NULL);

[mabstring addAttribute:(id)kCTFontAttributeName value:(id)font range:NSMakeRange(0, 4)];

【API使用系列】Core Text专题


//下划线

[mabstring addAttribute:(id)kCTUnderlineStyleAttributeName value:(id)[NSNumber numberWithInt: kCTUnderlineStyleDouble] range:NSMakeRange(0, 4)];

【API使用系列】Core Text专题

[if !supportLists]1 [endif]//下划线颜色

[mabstring addAttribute:(id)kCTUnderlineColorAttributeName value:(id)[UIColor redColor].CGColor range:NSMakeRange(0, 4)];

【API使用系列】Core Text专题

//设置字体简隔 eg:test 

longnumber = 10;

CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);

[mabstring addAttribute:(id)kCTKernAttributeName value:(id)num range:NSMakeRange(10, 4)];

【API使用系列】Core Text专题

//设置连字

long number = 1;

CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);

[mabstring addAttribute:(id)kCTLigatureAttributeName value:(id)num range: NSMakeRange(0, [str length])];

连字还不会使用,未看到效果。


//设置字体颜色

[mabstring addAttribute:(id)kCTForegroundColorAttributeName value:(id)[UIColor redColor].CGColor range:NSMakeRange(0, 9)];

【API使用系列】Core Text专题

//设置字体颜色为前影色

CFBooleanRef flag = kCFBooleanTrue;

[mabstring addAttribute:(id)kCTForegroundColorFromContextAttributeName value:(id)flag range:NSMakeRange(5, 10)];

无明显效果。


//设置空心字

long number = 2;

CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);

[mabstring addAttribute:(id)kCTStrokeWidthAttributeName value:(id)num range: NSMakeRange(0, [str length])];

【API使用系列】Core Text专题

//设置空心字

long number = 2;

CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);

[mabstring addAttribute:(id)kCTStrokeWidthAttributeName value:(id)num range:NSMakeRange(0, [str length])];

//设置空心字颜色

[mabstring addAttribute:(id)kCTStrokeColorAttributeName value:(id)[UIColor greenColor].CGColor range:NSMakeRange(0, [str length])];

【API使用系列】Core Text专题

在设置空心字颜色时,必须先将字体高为空心,否则设置颜色是没有效果的。


//对同一段字体进行多属性设置    

//红色

NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithObject:(id)[UIColor redColor].CGColor forKey:(id)kCTForegroundColorAttributeName];

//斜体

CTFontRef font = CTFontCreateWithName((CFStringRef)[UIFont italicSystemFontOfSize: 20].fontName, 40, NULL);

[attributes setObject:(id)font forKey:(id)kCTFontAttributeName];

//下划线

[attributes setObject:(id)[NSNumber numberWithInt:kCTUnderlineStyleDouble] forKey:(id)kCTUnderlineStyleAttributeName];

[mabstring addAttributes:attributes range:NSMakeRange(0, 4)];

【API使用系列】Core Text专题

1.4 绘制示例代码

最后是draw了。

-(void)characterAttribute

{

    NSString *str = @"This is a test of characterAttribute. 中文字符";

    NSMutableAttributedString *mabstring = [[NSMutableAttributedString alloc]initWithString:str];

    [mabstring beginEditing];

    /*

        long number = 1;

        CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);

        [mabstring addAttribute:(id)kCTCharacterShapeAttributeName value:(id)num range: NSMakeRange(0, 4)];

    */

    /*

    //设置字体属性

        CTFontRef font = CTFontCreateWithName(CFSTR("Georgia"), 40, NULL);

        [mabstring addAttribute:(id)kCTFontAttributeName value:(id)font range:NSMakeRange(0, 4)];

    */

    /*

    //设置字体简隔 eg:test 

    long number = 10;

    CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);

    [mabstring addAttribute:(id)kCTKernAttributeName value:(id)num range:NSMakeRange(10, 4)];

    */

    /*

    long number = 1;

    CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);

    [mabstring addAttribute:(id)kCTLigatureAttributeName value:(id)num range: NSMakeRange(0, [str length])];

    */

    /*

    //设置字体颜色

        [mabstring addAttribute:(id)kCTForegroundColorAttributeName value:(id)[UIColor redColor].CGColor range:NSMakeRange(0, 9)];

    */

    /*

        //设置字体颜色为前影色

        CFBooleanRef flag = kCFBooleanTrue;

        [mabstring addAttribute:(id)kCTForegroundColorFromContextAttributeName value:(id)flag range:NSMakeRange(5, 10)];

*/

    /*

        //设置空心字

        long number = 2;

        CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);

        [mabstring addAttribute:(id)kCTStrokeWidthAttributeName value:(id)num range: NSMakeRange(0, [str length])];

        //设置空心字颜色

        [mabstring addAttribute:(id)kCTStrokeColorAttributeName value:(id)[UIColor greenColor].CGColor range:NSMakeRange(0, [str length])];

    */

    /*

        long number = 1;

        CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);

        [mabstring addAttribute:(id)kCTSuperscriptAttributeName value:(id)num range:NSMakeRange(3, 1)];

    */

    /*

        //设置斜体字

        CTFontRef font = CTFontCreateWithName((CFStringRef)[UIFont italicSystemFontOfSize: 20].fontName, 14, NULL);

        [mabstring addAttribute:(id)kCTFontAttributeName value:(id)font range:NSMakeRange(0, 4)];

    */

    /*

    //下划线

        [mabstring addAttribute:(id)kCTUnderlineStyleAttributeName value:(id)[NSNumber numberWithInt: kCTUnderlineStyleDouble] range:NSMakeRange(0, 4)]; 

        //下划线颜色

        [mabstring addAttribute:(id)kCTUnderlineColorAttributeName value:(id)[UIColor redColor].CGColor range:NSMakeRange(0, 4)];

    */

    //对同一段字体进行多属性设置    

    //红色

    NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithObject:(id)[UIColor redColor].CGColor forKey:(id)kCTForegroundColorAttributeName];

    //斜体

    CTFontRef font = CTFontCreateWithName((CFStringRef)[UIFont italicSystemFontOfSize: 20].fontName, 40, NULL);

    [attributes setObject:(id)font forKey:(id)kCTFontAttributeName];

    //下划线

    [attributes setObject:(id)[NSNumber numberWithInt:kCTUnderlineStyleDouble] forKey:(id)kCTUnderlineStyleAttributeName];


    [mabstring addAttributes:attributes range:NSMakeRange(0, 4)];

    NSRange kk = NSMakeRange(0, 4);

    NSDictionary * dc = [mabstring attributesAtIndex:0 effectiveRange:&kk];

    [mabstring endEditing];

    NSLog(@"value = %@",dc);


    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)mabstring);

    CGMutablePathRef Path = CGPathCreateMutable();

    CGPathAddRect(Path, NULL ,CGRectMake(10 , 0 ,self.bounds.size.width-10 , self.bounds.size.height-10));

    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), Path, NULL);


    //获取当前(View)上下文以便于之后的绘画,这个是一个离屏。

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetTextMatrix(context , CGAffineTransformIdentity);

    //压栈,压入图形状态栈中.每个图形上下文维护一个图形状态栈,并不是所有的当前绘画环境的图形状态的元素都被保存。图形状态中不考虑当前路径,所以不保存

    //保存现在得上下文图形状态。不管后续对context上绘制什么都不会影响真正得屏幕。

    CGContextSaveGState(context);


    //x,y轴方向移动

    CGContextTranslateCTM(context , 0 ,self.bounds.size.height);

    //缩放x,y轴方向缩放,-1.0为反向1.0倍,坐标系转换,沿x轴翻转180度

    CGContextScaleCTM(context, 1.0 ,-1.0);

    CTFrameDraw(frame,context);


    CGPathRelease(Path);

    CFRelease(framesetter);

}  


- (void)drawRect:(CGRect)rect

{

    [self characterAttribute];

}  


1.5 用Quartz绘制文本

用Quartz绘制文本需要经过以下步骤:

    1、设置字体及字体大小

    2、设置绘制模式

    3、设置其他——描边色、填充色、背景区域

    4、如果需要变换,需要设置文本矩阵、旋转、缩放值

    5、绘制


CORETEXT框架图

【API使用系列】Core Text专题

    另对于Context的了解可以参考:http://www.padovo.com/blog/2013/01/31/study-coretext/


1.5.1 设置字体及字体大小

        Quartz 2D有两种方法设置字体及大小。CGContextSelectFont或CGContextSetFont+CGContextSetFontSize。CGContextSelectFont更简单一些。CGContextSetFont和CGContectSetFontSize麻烦一些,但你也可能想用Cocoa来设置字体然后进行绘制。因为Quartz在绘制文本上有一些限制。让我们再来比较一下两种方法的区别。

        如果对你的应用而言,使用MacRoman文本编码已经足够的话,可以使用CGContextSelectFont函数。在绘制文本时,调用CGContextShowTextAtPoint函数。CGContextSelectFont函数有4个参数:一个图形上下文,字体的PostScript字体名,字体大小(用户空间单位),以及文本的编码。

        如果想使用MacRoman以外的文本编码,应该使用CGContextSetFont和CGContextSetFontSize。必须为CGContextSetFont函数提供CGFont类型参数。调用CGFontCreateWithPlatformFont函数可以从ATS字体获得一个CGFont对象。绘制文本时,调用CGContextShowGlyphsAtPoint替代CGContextShowTextAtPoint。

        原因就在于,在将文本字节映射为字体符号时,需要指定一个文本编码,默认的文本编码是kCGEncodingFontSpecific,当你调用CGContextShowTextAtPoint时,不能保证一定会获得一个文本编码。由于你调用CGContextSetFont而不是CGContextSelectFont来指定字体,在CGContextSetFont中你并没有指定文本编码,你也就不能使用CGContextShowTextAtPoint来绘制文本。

        如果你要用这种方式设置字体,你必须用Cocoa或者自己实现将字符串映射为符号,这样你才能调用CGContextShowGlphsAtPoint。使用Cocoa绘制文本更简单,根本不需要任何Quartz2D函数。现在,你明白了使用Quartz绘制文本的一些限制,我们来看看使用CGContextSelectFont函数的一些例子。CGContextSelectFont函数的使用十分简单,但不建议你在MacRoman以外的编码下使用。清单16-1 显示了MyDrawText函数——用于绘制文本,如图16-1所示。代码后有详细的解释。

2 参考链接

NSAttributedString详解

http://www.cnblogs.com/zhw511006/archive/2012/09/21/2696700.html

IOS CoreText.framework ---基本用法

http://blog.csdn.net/fengsh998/article/details/8691823

IOS CoreText.framework ---行CTLineRef

http://blog.csdn.net/fengsh998/article/details/8701738

IOS CoreText.framework ---段落样子CTParagraphStyle

http://blog.csdn.net/fengsh998/article/details/8700627