iOS 给视图设置渐变色,同时给边框设置渐变色

请添加图片描述

- (void)layoutSubviews
{
    [super layoutSubviews];
    //背景渐变
    CAGradientLayer *gl = self.gradientLayer;
    gl.frame = CGRectMake(0, 0, CGRectGetWidth(self.gradientView.frame), CGRectGetHeight(self.gradientView.frame));
    gl.startPoint = CGPointMake(0.52, 1);
    gl.endPoint = CGPointMake(0.52, 0);
    gl.colors = @[(__bridge id)[UIColor colorWithRed:255/255.0 green:241/255.0 blue:241/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0].CGColor];
    gl.locations = @[@(0), @(1.0f)];
    //边框渐变
    CAGradientLayer *gradientLayer = self.gradientBorderLayer;
    gradientLayer.frame = CGRectMake(0, 0, CGRectGetWidth(self.gradientView.frame), CGRectGetHeight(self.gradientView.frame));
    gradientLayer.colors = @[(__bridge id)[UIColor colorWithHexString:@"0xFBD5D5"].CGColor, (__bridge id)[UIColor colorWithHexString:@"0xFBD5D5"].CGColor];
    gradientLayer.startPoint = CGPointMake(0, 0.5);
    gradientLayer.endPoint = CGPointMake(1, 0.5);
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.lineWidth = 1;
    maskLayer.path = [UIBezierPath bezierPathWithRoundedRect:self.gradientView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(8 * PLUS_SCALE, 8 * PLUS_SCALE)].CGPath;
    maskLayer.fillColor = UIColor.clearColor.CGColor;
    maskLayer.strokeColor = UIColor.redColor.CGColor;
    gradientLayer.mask = maskLayer;
}

#pragma mark - lazy load

- (UIView *)gradientView
{
    if (!_gradientView) {
        _gradientView = [[UIView alloc]  init];
        _gradientView.layer.masksToBounds = YES;
        _gradientView.layer.cornerRadius = 8 * PLUS_SCALE;
    }
    return _gradientView;
}

- (CAGradientLayer *)gradientLayer
{
    if (!_gradientLayer) {
        _gradientLayer = [[CAGradientLayer alloc] init];
    }
    return _gradientLayer;
}

- (CAGradientLayer *)gradientBorderLayer
{
    if (!_gradientBorderLayer) {
        _gradientBorderLayer = [[CAGradientLayer alloc] init];
    }
    return _gradientBorderLayer;
}

猜你喜欢

转载自blog.csdn.net/LIUXIAOXIAOBO/article/details/130445263