美文网首页
2021-11-09(带有描边效果的label)

2021-11-09(带有描边效果的label)

作者: ImmortalSummer | 来源:发表于2021-11-09 10:57 被阅读0次

带有描边效果的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

相关文章

网友评论

      本文标题:2021-11-09(带有描边效果的label)

      本文链接:https://www.haomeiwen.com/subject/jfymzltx.html