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];
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,758评论 0 17
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,171评论 1 32
  • 1 CALayer IOS SDK详解之CALayer(一) http://doc.okbase.net/Hell...
    Kevin_Junbaozi阅读 5,230评论 3 23
  • 是金子 总能发光 是种子 总会成苗 弦月等圆 春花含苞 暂时默默无闻 那是因为 出人头地的时候没到 攀登 还不...
    成运阅读 356评论 2 5
  • 杂项收藏大有市场 假如把古玩再分成“大古玩”与“小古玩”的话,那么,“大古玩”的概念是包括陶瓷器在内的所有非纸质收...
    瓷之醉阅读 140评论 0 0