CoreText 坐标系是以左下角为坐标原点。而我们经常使用的uikit是以左上角为坐标原点,因此 CoreText 中的布局完成后需要对其进行坐标系转换
一般做法: 获取当前上下文,将当前上下文坐标转换成CT坐标系,再将布局好的CT绘制到当前上下文即可
//获取当前上下文 CGContextRef context = UIGraphicsGetCurrentContext(); //翻转坐标系步骤 //设置当前文本矩阵 CGContextSetTextMatrix(context, CGAffineTransformIdentity); //文本沿y轴移动 CGContextTranslateCTM(context, 0, self.bounds.size.height); //文本翻转成为CoreText坐标系 CGContextScaleCTM(context, 1, -1);
CoreText文本布局
1.首先要确定布局时绘制的区域,其对应的类为CG(Mutable)PathRef
2.设置文本内容,其对应的类为NS(Mutable)AttributedString
3.根据文本内容配置其CTFramesetterRef
4.利用CTFramesetterRef得到CTFrame
//1.创建绘制区域,显示的区域可以用CGMUtablePathRef生成任意的形状 CGMutablePathRef path = CGPathCreateMutable(); CGPathAddRect(path, NULL, CGRectMake(20, 50, self.bounds.size.width - 40, self.bounds.size.height - 100)); //2.创建需要绘制的文字 NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:@"\tWhen I will learn CoreText, i think it will hard for me.But it is easy.\n\tIn fact,if you bengin learn, you can know that every thing is easy when you start.you just need some knowlages"]; //3.根据AttString生成CTFramesetterRef CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attString); CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, [attString length]), path, NULL);
文本属性设置