1、自定义UILabel
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface GC_Label : UILabel
// 设置文字描边:默认不描边,设置了描边颜色才会描边
/** 描边颜色 */
@property(nonatomic, strong) UIColor *stroke_color;
/** 描边宽度,默认为1 */
@property(nonatomic, assign) CGFloat stroke_width;
@end
NS_ASSUME_NONNULL_END
#import "GC_Label.h"
@implementation GC_Label
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = Clear_Color;
self.stroke_width = 1;
}
return self;
}
- (void)drawTextInRect:(CGRect)rect {
if (self.stroke_color) {
UIColor *temp_color = self.textColor;
CGContextRef context = UIGraphicsGetCurrentContext();
// 设置描边宽度
CGContextSetLineWidth(context, self.stroke_width);
CGContextSetLineJoin(context, kCGLineJoinRound);
CGContextSetTextDrawingMode(context, kCGTextStroke);
// 描边颜色
self.textColor = self.stroke_color;
[super drawTextInRect:rect];
// 文本颜色
self.textColor = temp_color;
CGContextSetTextDrawingMode(context, kCGTextFill);
[super drawTextInRect:rect];
}
else {
[super drawTextInRect:rect];
}
}
@end
2、使用与效果
_title_tv = [[GC_Label alloc] init];
_title_tv.textAlignment = NSTextAlignmentCenter;
_title_tv.textColor = [UIColor redColor];
_title_tv.stroke_color = [UIColor darkGrayColor];
_title_tv.stroke_width = 5;
_title_tv.text = @"温度26℃";