CoreText 绘制简单的纯文本

- (void)drawRect:(CGRect)rect {
    
    
    UIFont *font = [UIFont systemFontOfSize:15.0];
    NSString *str = @"哈哈哈哈哈哈哈哈合适的颠三倒四";
    // 创建setter
    
    CGContextRef context = UIGraphicsGetCurrentContext();

    
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    
    // 文字
    CTFontRef fontRef = CTFontCreateWithName((__bridge CFStringRef)font.fontName, font.pointSize, NULL);
    
    CGColorRef color = [UIColor yellowColor].CGColor;
    
    CGFloat lineSpace = 5.0;
    CTTextAlignment alignLeft = kCTTextAlignmentLeft;
    CTLineBreakMode breakModel = kCTLineBreakByWordWrapping;
    CTWritingDirection direction = kCTWritingDirectionLeftToRight;
    size_t count = 4;
    CTParagraphStyleSetting setting[4] = {
        {kCTParagraphStyleSpecifierAlignment,sizeof(alignLeft),&alignLeft},
        {kCTParagraphStyleSpecifierLineBreakMode,sizeof(breakModel),&breakModel},
        {kCTParagraphStyleSpecifierLineSpacingAdjustment,sizeof(lineSpace),&lineSpace},
        {kCTParagraphStyleSpecifierBaseWritingDirection,sizeof(direction),&direction},
        //            {},
    };
    
    
    CTParagraphStyleRef paragraRef = CTParagraphStyleCreate(setting, count);
    
    NSMutableAttributedString *attStrs = [[NSMutableAttributedString alloc] initWithString:str
                                                                                attributes:@{
                                                                                             (__bridge NSString*)kCTFontAttributeName:(__bridge id)fontRef,
                                                                                             (__bridge NSString*)kCTForegroundColorAttributeName:(__bridge id)color,
                                                                                             (__bridge NSString*)kCTParagraphStyleAttributeName:(__bridge id)paragraRef
                                                                                             
                                                                                             }];
    
    CFAttributedStringRef strRef = (__bridge CFAttributedStringRef)(attStrs);
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(strRef);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, self.bounds);
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, CFAttributedStringGetLength(strRef)), path, NULL);
    CTFrameDraw(frame, context);
    
    // 释放
    CGPathRelease(path);
    CFRelease(fontRef);
    CFRelease(paragraRef);
    CFRelease(frameSetter);
    CFRelease(frame);
    

    
    
}



效果:

CoreText 绘制简单的纯文本_第1张图片
Simulator Screen Shot 2017年2月28日 上午11.16.58.png

参考文章:

唐巧iOS进阶 http://blog.devtang.com/2015/06/27/using-coretext-1/

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