CoreText绘制文本

- (void)drawRect:(CGRect)rect {
    // Drawing code
    CGContextRef ref = UIGraphicsGetCurrentContext();
    
    // 反转坐标
    CGContextTranslateCTM(ref, 0, self.bounds.size.height);
    CGContextScaleCTM(ref, 1.0, -1.0);
    CGContextSetTextMatrix(ref, CGAffineTransformIdentity);
    
    // 创建矩形的路劲  置顶文字的绘制范围
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, self.bounds);
    
    // 4.创建富文本
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:@"Hello, World! I know nothing in the world that has as much power as a word. Sometimes I write one, and I look at it, until it begins to shine." attributes:@{NSForegroundColorAttributeName:[UIColor orangeColor],NSFontAttributeName:[UIFont systemFontOfSize:15]}];

    // 5.根据attrStr初始化CTFramesetterRef
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef )attrStr);

    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
    // 绘制内容
    CTFrameDraw(frame, ref);
    
    // 8. 释放内存
    CFRelease(frame);
    CFRelease(framesetter);
    CFRelease(path);
    CFRelease(ref);
}

你可能感兴趣的:(CoreText绘制文本)