美文网首页
自定义绘制label

自定义绘制label

作者: 狒狒James_Leo | 来源:发表于2017-09-14 11:04 被阅读0次
    //
    //  PHCLabel.m
    //  TextKit
    //
    //  Created by phc on 16/8/27.
    //  Copyright © 2016年 phc. All rights reserved.
    //
    
    #import "PHCLabel.h"
    #import <CoreText/CoreText.h>
    @implementation PHCLabel
    
    -(instancetype)initWithFrame:(CGRect)frame{
        
        
        if ([super initWithFrame:frame]) {
            
            //默认的设置
            self.textColor = [UIColor blackColor];
            self.textFont = [UIFont systemFontOfSize:15.0];
        }
        return self;
    }
    
    -(void)drawRect:(CGRect)rect{
        
        /**
          CTFrame
          CTLine
          CTRun
         */
        NSDictionary *dic = @{
                              NSForegroundColorAttributeName :[UIColor redColor]
                              
                              };
        NSMutableAttributedString  *attribute = [[NSMutableAttributedString alloc] initWithString:self.text attributes:dic];
       
        [attribute addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:[self.text rangeOfString:@"ddd"]];
        
        //设置器
        CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)  attribute);
        
        //获取路径
        CGMutablePathRef path = CGPathCreateMutable();
        //绘制具体的路径
        CGPathAddRect(path, NULL, self.bounds);
        
        //CTFrame
        CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
        //获取上下文
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        
        //改变坐标系统
        
        CGContextTranslateCTM(context, 0, CGRectGetHeight(self.bounds));
        CGContextScaleCTM(context, 1, -1);
        
        //绘制
        CTFrameDraw(frame, context);
        
    }
    @end
    
    
    

    相关文章

      网友评论

          本文标题:自定义绘制label

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