带有描边效果的label
// LDStrokeLabel.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface LDStrokeLabel : UILabel
/// 初始化一个带有描边效果的label; strokeColor: 描边颜色 (默认宽度为1)
+(instancetype)labelWithStrokeColor:(UIColor *)strokeColor;
/// 初始化一个带有描边效果的label; strokeColor: 描边颜色; strokeWidth: 描边宽度
+(instancetype)labelWithStrokeColor:(UIColor *)strokeColor andStrokeWidth:(CGFloat)strokeWidth;
@end
NS_ASSUME_NONNULL_END
// LDStrokeLabel.m
#import "LDStrokeLabel.h"
@interface LDStrokeLabel()
@property(nonatomic, strong) UIColor *strokeColor;// 描边颜色
@property(nonatomic, assign) CGFloat strokeWidth; // 描边宽度
@end
@implementation LDStrokeLabel
/// 初始化一个带有描边效果的label; strokeColor: 描边颜色
+(instancetype)labelWithStrokeColor:(UIColor *)strokeColor{
return [self labelWithStrokeColor:strokeColor andStrokeWidth:1];
}
/// 初始化一个带有描边效果的label; strokeColor: 描边颜色; strokeWidth: 描边宽度
+(instancetype)labelWithStrokeColor:(UIColor *)strokeColor andStrokeWidth:(CGFloat)strokeWidth{
LDStrokeLabel *label = LDStrokeLabel.new;
label.strokeColor = strokeColor;
label.strokeWidth = strokeWidth;
return label;
}
- (void)drawTextInRect:(CGRect)rect {
if (self.strokeColor == nil) {
[super drawTextInRect:rect];
return;
}
// 将文字前移描边宽度的距离,不然最后部分的描边会被切掉
rect = CGRectMake(rect.origin.x-self.strokeWidth, rect.origin.y, rect.size.width, rect.size.height);
UIColor *textColor = self.textColor;
if (textColor == nil) {
textColor = UIColor.whiteColor;
}
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, self.strokeWidth); // 设置描边宽度
CGContextSetLineJoin(context, kCGLineJoinRound);
CGContextSetTextDrawingMode(context, kCGTextStroke);
self.textColor = self.strokeColor; // 描边颜色
[super drawTextInRect:rect];
self.textColor = textColor; // 文本颜色
CGContextSetTextDrawingMode(context, kCGTextFill);
[super drawTextInRect:rect];
}
@end
网友评论