iOS视图渐变色及贝塞尔高效圆角

开发中经常有需要为标签或按钮添加渐变底色,让UI看起来更舒适(逼格更高),下面的方法可以直接添加到项目的通用工具类中,如有需要多种渐变式样,其中颜色变量c1、c2、c3可作为方法参数传入更加方便。 自己动手丰衣足食也不用麻烦UI妹纸了。

1.给目标控件添加渐变色

+ (void)addGradientToLayer:(UIView *)aimView{
    
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.contentsScale = [UIScreen mainScreen].scale;
    gradient.bounds = CGRectMake(0, 0, CGRectGetWidth(aimView.frame), CGRectGetHeight(aimView.frame));
    gradient.position = CGPointMake(CGRectGetMidX(aimView.bounds), CGRectGetMidY(aimView.bounds));    //设置锚点
    
    UIColor *c1 = [UIColor colorWithRed:113.0/255.0 green:201.0/255.0 blue:247.0/255.0 alpha:1];
    UIColor *c2 = [UIColor colorWithRed:93.0/255.0 green:180.0/255.0 blue:247.0/255.0 alpha:1];
    UIColor *c3 = [UIColor colorWithRed:72.0/255.0 green:159.0/255.0 blue:247.0/255.0 alpha:1];
    gradient.colors = @[(id)c1.CGColor,(id)c2.CGColor,(id)c3.CGColor];
    gradient.locations = @[@0,@0.5,@1];
    //startPoint 和 endPoint连起来即为渐变路径(以下为中间从左至右渐变)
    gradient.startPoint = CGPointMake(0, 0.5);
    gradient.endPoint = CGPointMake(1, 0.5);
    
    [aimView.layer addSublayer:gradient];
}

2.贝塞尔曲线高效设置控件圆角及边框颜色

/*  
    1.不需要设置边框颜色时 传nil即可
    2.设置控件圆角及边框颜色
*/
+ (void)setupCorner:(UIView *)aimView size:(CGSize)cornerSize borderColor:(UIColor *)borderColor{

    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:aimView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:cornerSize];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = aimView.bounds;
    maskLayer.path = maskPath.CGPath;
    maskLayer.lineWidth = 1;
    
    //设置控件边框颜色
    if (borderColor){
        CAShapeLayer *borderLayer = [CAShapeLayer layer];
        borderLayer.frame = aimView.bounds;
        borderLayer.lineWidth = 1.f;
        borderLayer.strokeColor = borderColor.CGColor;
        borderLayer.fillColor = [UIColor clearColor].CGColor;
        
        UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:aimView.bounds cornerRadius:cornerSize.width];
        maskLayer.path = bezierPath.CGPath;
        borderLayer.path = bezierPath.CGPath;
        
        [aimView.layer insertSublayer:borderLayer atIndex:0];
    }
    [aimView.layer setMask:maskLayer];
}

你可能感兴趣的:(iOS视图渐变色及贝塞尔高效圆角)