coreText之实现文字突出效果

        年前一直在纠结文字样式问题,领导总觉得聊天那块的文字字体不好看,尝试了好几种方法后调出一种效果。

1.先看一下效果图

coreText之实现文字突出效果_第1张图片

2.实现

    要点就是在文字周围加上一个白色边,具代码实现如下:

// 步骤1:得到当前用于绘制画布的上下文,用于后续将内容绘制在画布上

// 因为Core Text要配合Core Graphic 配合使用的,如Core Graphic一样,绘图的时候需要获得当前的上下文进行绘制

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetShadowWithColor(context, CGSizeMake(0, 1), 0.5,  [UIColor colorWithRed:0 green:0 blue:0 alpha:0.9].CGColor);//给文字添加阴影

// 步骤2:翻转当前的坐标系(因为对于底层绘制引擎来说,屏幕左下角为(0,0))

CGContextSetTextMatrix(context, CGAffineTransformIdentity);

CGAffineTransform flipVertical = CGAffineTransformMake(1,0,0,-1,0,self.bounds.size.height);

CGContextConcatCTM(context, flipVertical);//将当前context的坐标系进行flip

NSMutableAttributedString* usernameattribute = [[NSMutableAttributedStringalloc]initWithString:@"coreTextTest"];

[usernameattribute addAttributes:@{(id)kCTFontAttributeName:[UIFontboldSystemFontOfSize:17],(id)kCTForegroundColorAttributeName:[UIColor colorWithRed:254.0/255.0 green:254.0/255.0 blue:65.0/255.0 alpha:1]} range:NSMakeRange(0,usernameattribute.length)];//设置字体颜色

//给文字加上一个白色的边框能使字体显示出发光立体效果

[usernameattribute addAttribute:(id)kCTStrokeWidthAttributeName value:@(-0.4) range:NSMakeRange(0, [usernameattribute length])];

[usernameattribute addAttribute:(id)kCTStrokeColorAttributeName value:(id)[UIColor whiteColor].CGColor range:NSMakeRange(0, [usernameattribute length])];

// 步骤3:创建绘制区域

CGMutablePathRef path = CGPathCreateMutable();

CGRect bounds = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);

CGPathAddRect(path, NULL, bounds);

// 步骤5:根据AttributedString生成CTFramesetterRef

CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)username);

CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, [username length]), path, NULL);

// 步骤6:进行绘制

CTFrameDraw(frame, context);

// 步骤7.内存管理

CFRelease(frame);

CFRelease(path);

CFRelease(frameSetter);

注 :重点是如下两行代码,这两行代码会使字体出现突出立体效果

[usernameattribute addAttribute:(id)kCTStrokeWidthAttributeName value:@(-0.4) range:NSMakeRange(0, [usernameattribute length])];

[usernameattribute addAttribute:(id)kCTStrokeColorAttributeName value:(id)[UIColor whiteColor].CGColor range:NSMakeRange(0, [usernameattribute length])];

你可能感兴趣的:(coreText之实现文字突出效果)