? ? ? ? 年前一直在糾結(jié)文字樣式問題典予,領(lǐng)導(dǎo)總覺得聊天那塊的文字字體不好看甜滨,嘗試了好幾種方法后調(diào)出一種效果。
1.先看一下效果圖
2.實(shí)現(xiàn)
? ? 要點(diǎn)就是在文字周圍加上一個(gè)白色邊瘤袖,具代碼實(shí)現(xiàn)如下:
// 步驟1:得到當(dāng)前用于繪制畫布的上下文衣摩,用于后續(xù)將內(nèi)容繪制在畫布上
// 因?yàn)镃ore Text要配合Core Graphic 配合使用的,如Core Graphic一樣捂敌,繪圖的時(shí)候需要獲得當(dāng)前的上下文進(jìn)行繪制
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetShadowWithColor(context, CGSizeMake(0, 1), 0.5,? [UIColor colorWithRed:0 green:0 blue:0 alpha:0.9].CGColor);//給文字添加陰影
// 步驟2:翻轉(zhuǎn)當(dāng)前的坐標(biāo)系(因?yàn)閷?duì)于底層繪制引擎來說昭娩,屏幕左下角為(0,0))
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGAffineTransform flipVertical = CGAffineTransformMake(1,0,0,-1,0,self.bounds.size.height);
CGContextConcatCTM(context, flipVertical);//將當(dāng)前context的坐標(biāo)系進(jìn)行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)];//設(shè)置字體顏色
//給文字加上一個(gè)白色的邊框能使字體顯示出發(fā)光立體效果
[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:創(chuàng)建繪制區(qū)域
CGMutablePathRef path = CGPathCreateMutable();
CGRect bounds = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
CGPathAddRect(path, NULL, bounds);
// 步驟5:根據(jù)AttributedString生成CTFramesetterRef
CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)username);
CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, [username length]), path, NULL);
// 步驟6:進(jìn)行繪制
CTFrameDraw(frame, context);
// 步驟7.內(nèi)存管理
CFRelease(frame);
CFRelease(path);
CFRelease(frameSetter);
注 :重點(diǎn)是如下兩行代碼黍匾,這兩行代碼會(huì)使字體出現(xiàn)突出立體效果
[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])];