序言
想实现一个输入框的边框颜色渐变 效果流动的动效,研究了下渐变相关的内容,写了个小demo
代码
话不多说 直接上代码
UIView *sweepGradientView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 320, 320)];
[self.view addSubview:sweepGradientView];
self.gradientLayer = [CAGradientLayer layer];
self.gradientLayer.type = kCAGradientLayerConic; //只支持iOS12以上
UIColor *color1 = [UIColor colorWithRed:0x24/255.0 green:0x96/255.0 blue:0xFF/255.0 alpha:1.0]; // 2496FF
UIColor *color2 = [UIColor colorWithRed:0x6C/255.0 green:0x60/255.0 blue:0xE3/255.0 alpha:1.0]; // 6C60E3
UIColor *color3 = [UIColor colorWithRed:0xB3/255.0 green:0x77/255.0 blue:0xFF/255.0 alpha:1.0]; // B377FF
UIColor *color4 = [UIColor colorWithRed:0x31/255.0 green:0x45/255.0 blue:0xFF/255.0 alpha:1.0]; // 3145FF
self.gradientLayer.colors = @[
(__bridge id)color1.CGColor,
(__bridge id)color2.CGColor,
(__bridge id)color3.CGColor,
(__bridge id)color4.CGColor,
(__bridge id)color1.CGColor
];
self.gradientLayer.startPoint = CGPointMake(0.5, 0.5);
self.gradientLayer.endPoint = CGPointMake(0, 0.5);
self.gradientLayer.locations = @[@0.0, @0.25, @0.5, @0.75, @1.0];
self.gradientLayer.frame = sweepGradientView.bounds;
[sweepGradientView.layer addSublayer:self.gradientLayer];
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, 110, 300, 100)];
view.backgroundColor = [UIColor clearColor];
view.layer.cornerRadius = 50;
view.layer.masksToBounds = YES;
[sweepGradientView addSubview:view];
UIView *whiteBackgroundView = [[UIView alloc] initWithFrame:sweepGradientView.bounds];
whiteBackgroundView.backgroundColor = [UIColor whiteColor];
[sweepGradientView addSubview:whiteBackgroundView];
[sweepGradientView sendSubviewToBack:whiteBackgroundView];
CALayer *maskLayer = [CALayer layer];
maskLayer.backgroundColor = [UIColor blackColor].CGColor;
maskLayer.frame = view.frame;
sweepGradientView.layer.mask = maskLayer;
maskLayer.cornerRadius = view.layer.cornerRadius;
CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
rotationAnimation.fromValue = @(0.0);
rotationAnimation.toValue = @(2 * M_PI);
rotationAnimation.duration = 4.0;
rotationAnimation.repeatCount = HUGE_VALF;
[self.gradientLayer addAnimation:rotationAnimation forKey:@"rotationAnimation"];