UILabel 如何实现背景色、边框色从左到右的渐变

#import

typedef NS_ENUM(NSUInteger, GradientStyle) {

    GradientStyleFill = 1 << 0,

    GradientStyleStroke,

};

@interface BorderGradientLabel : UILabel


@property (nonatomic, assign) GradientStyle gradientStyle;

- (instancetype)initWithFrame:(CGRect)frame style:(GradientStyle)gradientStyle cornerRadius:(CGFloat)radius;


@end

/**

 * 注意 设置圆角 通过radius设置即可,不要在外部使用layer.masksToBounds设置否则文字会显示不出来

 * 注意 改变gradientStyle后需要调用一下setNeedsDisplay方法,才能起到效果

 */



#import "BorderGradientLabel.h"


@interface BorderGradientLabel()

@property (nonatomic, assign) CGFloat radius;

@end


@implementation BorderGradientLabel

- (instancetype)initWithFrame:(CGRect)frame style:(GradientStyle)gradientStyle cornerRadius:(CGFloat)radius{

    if (self = [super initWithFrame:frame]) {

        _gradientStyle = gradientStyle;

        _radius = radius;

    }

    return self;

}

- (void)drawRect:(CGRect)rect {

    // Drawing code

    [super drawRect:rect];

    CGFloat radius = self.radius;

    CAGradientLayer *gradientLayer = [CAGradientLayer layer];

    gradientLayer.colors = @[(__bridge id)[UIColor redColor].CGColor, (__bridge id)[UIColor cyanColor].CGColor];

    // locations标识了,在0.0到0.5这个区间内,实现第一个颜色到第二个颜色渐变过程

    gradientLayer.locations = @[@0.0, @0.5];

    // startPoint和endPoint标识了沿着什么方向渐变

    gradientLayer.startPoint = CGPointMake(0, 0);

    gradientLayer.endPoint = CGPointMake(1.0, 0);

    gradientLayer.frame = self.bounds;

    gradientLayer.cornerRadius = radius;

    

    if (self.gradientStyle == GradientStyleStroke) {

        

        //创建背景圆环

        CAShapeLayer *trackLayer = [CAShapeLayer layer];

        trackLayer.frame = self.bounds;

        //清空填充色

        trackLayer.fillColor = [UIColor clearColor].CGColor;

        //设置画笔颜色 即圆环背景色

        trackLayer.strokeColor =  [UIColor colorWithRed:170/255.0 green:210/255.0 blue:254/255.0 alpha:1].CGColor;

        CGFloat lineW = 3;

        trackLayer.lineWidth = lineW;

        //设置画笔路径

        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(self.bounds, lineW * 0.5, lineW * 0.5) cornerRadius:radius];

        //path 决定layer将被渲染成何种形状

        trackLayer.path = path.CGPath;

        gradientLayer.mask = trackLayer;

    }

    [self.layer insertSublayer:gradientLayer atIndex:0];

}


- (void)setBackgroundColor:(UIColor *)backgroundColor {

    

}


@end


你可能感兴趣的:(iOS,绘图,与,文本)