天天看点

基于CoreText的基础排版引擎

不带图文的排版引擎:

注意:导入头文件

#import <CoreText/CoreText.h>

- (void)drawRect:(CGRect)rect {

    // Drawing code

    [super drawRect:rect];

    //步骤1:得到当前绘制画布的上下文,用于后续将内容绘制在画布上。

    CGContextRef context = UIGraphicsGetCurrentContext();

    //步骤2:将坐标系上下翻转。对于底层的绘画引擎来说,屏幕的左下角是(0,0)。而相对于UIKit来说,左下角是(0,0)坐标。所以我们为了之后的坐标系描述UIKit来做,现在这里做一个坐标系的上下翻转操作。翻转之后,底层和上层的(0,0)坐标就是重合的了

    CGContextSetTextMatrix(context, CGAffineTransformIdentity);

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

    CGContextScaleCTM(context, 1.0, -1.0);

    //步骤3:创建绘制区域,coreText本身支持各种文字排版的区域

    CGMutablePathRef path = CGPathCreateMutable();

//    CGPathAddRect(path, NULL, self.bounds);

    CGPathAddEllipseInRect(path, NULL, self.bounds);

    //步骤4

    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc]initWithString:@"Hello world!创建绘制区域coreText本身支持各种文字排版的区域 为了加深理解,建议读者将CGPathAddRect(path, NULL, self.bounds);这步骤的代码替换成CGPathAddEllipseInRect(path, NULL, self.bounds);"];

    [attString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(1, 7)];

    CTFramesetterRef frameseter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attString);

    CTFrameRef frame = CTFramesetterCreateFrame(frameseter, CFRangeMake(0, [attString length]), path, NULL);

    //步骤5

    CTFrameDraw(frame, context);

    //步骤6

    CFRelease(frame);

    CFRelease(path);

    CFRelease(frameseter);

}

继续阅读