美文网首页
CoreText绘制文本

CoreText绘制文本

作者: 谭谭谭思密达 | 来源:发表于2018-07-18 13:51 被阅读4次
- (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绘制文本

      本文链接:https://www.haomeiwen.com/subject/iiyopftx.html