说白点就是一个CAGradientLayer,直接上封装代码
/**
@param view 要设置渐变色的view
@param fromColor 渐变色的起始颜色
@param toColor 渐变色的终止颜色
*/
-(void)addGradientLayerWithView:(UIView *)view fromColor:(UIColor *)fromColor toColor:(UIColor *)toColor{
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.cornerRadius = 10;
gradientLayer.frame = view.bounds;
gradientLayer.colors = @[(__bridge id)fromColor.CGColor,(__bridge id)toColor.CGColor];
gradientLayer.startPoint = CGPointMake(0,1);
gradientLayer.endPoint = CGPointMake(1,1);
gradientLayer.locations = @[@0,@1];
[view.layer insertSublayer:gradientLayer atIndex:0];
}
调用:
UIButton *btn = [[UIButton alloc]init];
[btn setTitle:@"登录" forState:0];
[self.view addSubview:btn];
[btn makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(20);
make.right.equalTo(-20);
make.centerY.equalTo(self.view);
make.height.equalTo(55);
}];
[btn layoutIfNeeded];
简单粗暴!
2.同样,稍加扩展一个渐变边框就出现了
-(void)addGradientLayerWithView:(UIView *)view fromColor:(UIColor *)fromColor toColor:(UIColor *)toColor{
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = view.bounds;
gradientLayer.colors = @[(__bridge id)fromColor.CGColor,(__bridge id)toColor.CGColor];
gradientLayer.startPoint = CGPointMake(0,1);
gradientLayer.endPoint = CGPointMake(1,1);
gradientLayer.locations = @[@0,@1];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:gradientLayer.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(10, 10)];
CAShapeLayer *mask = [CAShapeLayer layer];
mask.contentsScale = [UIScreen mainScreen].scale;
mask.lineWidth = 3;
mask.path = path.CGPath;
/*
fillColor 是shapeLayer的填充色,默认是黑色,建议设置成nil或者是透明色clearColor
strokeColor 是border的描边色,如果设置成clearColor的话就不会绘制出来border了,这里随便一个颜色就是让其能够绘制出来,实际使用的是渐变色
*/
mask.fillColor = UIColor.clearColor.CGColor;
mask.strokeColor = UIColor.whiteColor.CGColor;
gradientLayer.mask = mask;
[view.layer insertSublayer:gradientLayer atIndex:0];
}
截屏2022-05-13 14.21.42.png
网友评论