天天看点

iOS任意圆角与View渐变

开发中经常不规则圆角及渐变的需求,看着挺复杂,其实实现只需要几句代码。先看看效果图,右上角的View既包含不规则的圆角,又包含渐变,里面的按钮也包含渐变

iOS任意圆角与View渐变

实现代码:

self.totalView = [[UIView alloc] initWithFrame:CGRectMake(kScreenWidth-140, 20, 140, 38)];
    // 渐变
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = self.totalView.bounds;
    gradient.colors = @[(id)[kColorWithFloat(0xFFDFA1) CGColor], (id)[kColorWithFloat(0xFFA962) CGColor]];
    gradient.startPoint = CGPointMake(0, 0.5);
    gradient.endPoint = CGPointMake(1, 0.5);
    gradient.locations = @[@(0), @(1.0f)];
    [self.totalView.layer insertSublayer:gradient atIndex:0];

    // 圆角 裁掉左上和左下
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.totalView.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerTopLeft cornerRadii:CGSizeMake(19, 19)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.totalView.bounds;
    maskLayer.path = maskPath.CGPath;
    self.totalView.layer.mask = maskLayer;


    // startPoint和endPoint的取值范围是0~1
    // (0.0, 0.5)-->(1.0, 0.5)   x变y不变  从左到右
    // (0.5, 0.0)-->(0.5, 1.0)   y变x不变  从上到下
    // (0.0, 0.0)-->(1.0, 1.0)   左上到右下渐变
           

继续阅读