iOS

渐变边框

渐变边框

920 发布: 2024/5/10 07:36 本文总阅读量
渐变边框
+(CAGradientLayer *)setGradientBorder:(UIView *)dealView alphaBg:(BOOL)alphaBg borderWidth:(int)borderWidth lineWidth:(CGFloat)lineWidth {
    // 透明背景
    if(alphaBg){
        dealView.backgroundColor = hexColor(@"#000000", 0.26);
    }
    // 创建 CAGradientLayer
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = dealView.bounds;
    gradientLayer.startPoint = CGPointMake(0, 1);
    gradientLayer.endPoint = CGPointMake(1, 1);
    
    // 设置渐变的颜色数组
    gradientLayer.colors = @[
        (id)hexColor(@"#F1D799", 1).CGColor,
        (id)hexColor(@"#D1ABC3", 1).CGColor,
        (id)hexColor(@"#897FC0", 1).CGColor,
    ];
    gradientLayer.locations = @[
        @0,
        @0.3,
        @1.0
    ];
    CGRect fillRect = CGRectMake(borderWidth, borderWidth, dealView.bounds.size.width-borderWidth*2, dealView.bounds.size.height-borderWidth*2);
    // 创建 UIBezierPath,用于设置边框路径
    UIBezierPath *borderPath = [UIBezierPath bezierPathWithRoundedRect:fillRect cornerRadius:dealView.layer.cornerRadius];
    
    // 创建 CAShapeLayer,用于设置边框样式
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = borderPath.CGPath;
    shapeLayer.fillColor = hexColor(@"#000000", 0).CGColor;
    shapeLayer.strokeColor = hexColor(@"#000000", 1).CGColor;
    shapeLayer.lineWidth = lineWidth;
    
    gradientLayer.mask = shapeLayer;
    [dealView.layer addSublayer:gradientLayer];
    return gradientLayer;
}

渐变背景
+(CAGradientLayer *)setGradientBg:(UIView *)dealView {
    // 创建 CAGradientLayer
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = dealView.bounds;
    gradientLayer.startPoint = CGPointMake(0, 1);
    gradientLayer.endPoint = CGPointMake(1, 1);
    
    // 设置渐变的颜色数组
    gradientLayer.colors = @[
        (id)hexColor(@"#F1D799", 1).CGColor,
        (id)hexColor(@"#D1ABC3", 1).CGColor,
        (id)hexColor(@"#897FC0", 1).CGColor,
    ];
    gradientLayer.locations = @[
        @0,
        @0.3,
        @1.0
    ];
    
    [dealView.layer insertSublayer:gradientLayer atIndex:0];
    return gradientLayer;
}