UILabel显示带颜色边的文字

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dolacmeng/article/details/81204469

需求如图,UILabel要实现带红色边的文字显示。
这里写图片描述

1、新建UILabel的子类JXBorderLabel

2、重写drawRect:方法

#import "JXBorderLabel.h"

@implementation JXBorderLabel

- (void)drawRect:(CGRect)rect {
    //1.获取上下文
    CGContextRef context = UIGraphicsGetCurrentContext();

    //2.给上下文线段设置线宽,画出文本
    CGContextSetLineWidth(context, 5);
    CGContextSetLineJoin(context, kCGLineJoinRound);
    CGContextSetTextDrawingMode(context, kCGTextStroke);
    self.textColor = UIColor.redColor;
    [super drawRect:rect];

    //3.绘制原本的文字
    CGContextSetTextDrawingMode(context, kCGTextFill);
    [UIColor.whiteColor setFill];
    self.textColor = UIColor.whiteColor;
    [super drawRect:rect];
}

@end

3、使用
(1)xib/storyboard使用时,将UILabel设置为JXBorderLabel类。
(2)代码使用时,创建UILabel,替换为创建JXBorderLabel

完整代码:https://github.com/dolacmeng/JXBorderLabelDemo

猜你喜欢

转载自blog.csdn.net/dolacmeng/article/details/81204469