自定义绘制label

//
//  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


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容