CoreText 基础

坐标系

如果你了解过 iOS UIKit,你就知道坐标的原点就在屏幕的左上角,但是底层Core Graphics的context使用的坐标系的原点是在屏幕的左下角。那从底层到上层一定是做了转变。苹果官方例图

图1.png

上图可以看到,坐标系发生了改变,变成了我们最熟悉的模样。具体代码实现如下:

 - (void)drawRect:(CGRect)rect{
    [super drawRect:rect];

    //获得当前的Graphics Context
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    //向上平移一个视图高度的距离
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    //围绕x轴的翻转
    CGContextScaleCTM(context, 1.0, -1.0);
   }

写一小段文字效果:

图2.png
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];

//获得当前的Graphics Context
CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetTextMatrix(context, CGAffineTransformIdentity);
//向上平移一个视图高度的距离
CGContextTranslateCTM(context, 0, self.bounds.size.height);
//围绕x轴的翻转
CGContextScaleCTM(context, 1.0, -1.0);


// 创建绘制区域
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, self.bounds);

//文字相关的属性都是由NSMutableAttributedString来设置的
NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:@"爱笑的女孩运气不会太差,太差你倒是也笑不出来的"];
[att addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:25] range:NSMakeRange(4, 5)];
[att addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20] range:NSMakeRange(11, 4)];
[att addAttribute:NSForegroundColorAttributeName value:[UIColor purpleColor] range:NSMakeRange(3, 4)];

//上下行的间距
CGFloat lineSpace = 30 ;

const CFIndex num = 1;
CTParagraphStyleSetting theSettings[num] = {
            {kCTParagraphStyleSpecifierLineSpacingAdjustment,sizeof(CGFloat),&lineSpace},
};
CTParagraphStyleRef theParagraphRef = CTParagraphStyleCreate(theSettings, num);

// NSMakeRange(0, att.length) 整段文字长度
[att addAttribute:NSParagraphStyleAttributeName value:(__bridge id)(theParagraphRef) range:NSMakeRange(0, att.length)];



//排版
CTFramesetterRef framesetter =
CTFramesetterCreateWithAttributedString((CFAttributedStringRef)att);
CTFrameRef frame =
CTFramesetterCreateFrame(framesetter,
                         CFRangeMake(0, [att length]), path, NULL);

//绘制
CTFrameDraw(frame, context);

//释放
CFRelease(theParagraphRef);
CFRelease(frame);
CFRelease(path);
CFRelease(framesetter);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转载请带上出处, 谢谢. 一个 Graphics Context 代表一个绘制目标, 它包含绘制系统用于完成绘制指...
    Falme丶阅读 5,764评论 0 2
  • 1.Quartz 2D是什么? •Quartz 2D以PDF的规范为基础的图形库,用来绘制二维文字和图形,允许相同...
    空白Null阅读 3,240评论 0 1
  • Core Graphics Framework是一套基于C的API框架,使用了Quartz作为绘图引擎。它提供了低...
    ShanJiJi阅读 5,540评论 0 20
  • 转载文章。原文传送门 1.Quartz 2D是什么? •Quartz 2D以PDF的规范为基础的图形库,用来绘制二...
    大爷你的伞阅读 3,741评论 0 3
  • 我是一名钓鱼爱好者,喜欢背着装备跟着大人跋山涉水,就为了找一个好的钓鱼地点,通常都是早上六七点出发,晚上六七点回来...
    繁华故城阅读 3,265评论 0 3