1. 程式人生 > >IOS 給UILabel字體加一個帶顏色的邊框

IOS 給UILabel字體加一個帶顏色的邊框

xxxxxx bsp right elf 實現 ttext end drawtext uilabel

今天做項目碰見一個UI效果,給字體加一圈白邊,看起來就像是加了一個背景,思路就是繼承一個UILabel,重新覆寫drawTextInRect方法,就可以簡單實現這個效果,上代碼:

 1 //
 2 //  HGLLabel.m
 3 //  xxxxxxxxxx.xxx
 4 //
 5 //  Created by xxxxx on 2017/12/23.
 6 //  Copyright ? 2017年 xxxx. All rights reserved.
 7 //
 8 
 9 #import "HGLLabel.h"
10 
11 @implementation HGLLabel
12 
13 - (void)drawTextInRect:(CGRect)rect {
14 CGSize shadowOffset = self.shadowOffset; 15 UIColor *textColor = self.textColor; 16 17 CGContextRef c = UIGraphicsGetCurrentContext(); 18 CGContextSetLineWidth(c, 8.0);//字體邊緣的寬度 19 CGContextSetLineJoin(c, kCGLineJoinRound); 20 21 CGContextSetTextDrawingMode(c, kCGTextStroke);
22 self.textColor = [UIColor whiteColor];//字體邊緣加的顏色 23 [super drawTextInRect:rect]; 24 25 CGContextSetTextDrawingMode(c, kCGTextFill); 26 self.textColor = textColor; 27 self.shadowOffset = CGSizeMake(0, 0); 28 [super drawTextInRect:rect]; 29 30 self.shadowOffset = shadowOffset;
31 } 32 33 @end

註釋很清楚,不多說。

IOS 給UILabel字體加一個帶顏色的邊框