效果
由于是demo我们这个直接拖拽xib实现布局
- 首先我们为特效这个视图单独建一个
AIAnimationMaskLabel
关联起来
- 接下来配置
gradientLayer
- 起始点
// Configure the gradient here
_gradientLayer.startPoint = CGPointMake(0., .5);
_gradientLayer.endPoint = CGPointMake(1., .5);

- 颜色
NSArray *colors = @[
(__bridge id)[UIColor blackColor].CGColor,
(__bridge id)[UIColor whiteColor].CGColor,
(__bridge id)[UIColor blackColor].CGColor,
];
_gradientLayer.colors = colors;
- 位置
NSArray *locations = @[@0.25,@.5,@.75];
_gradientLayer.locations = locations;
现在gradientLayer应该是这样的
然后在layoutSubviews()
方法中设置
-(void)layoutSubviews {
[super layoutSubviews];
self.gradientLayer.frame = CGRectMake(-self.bounds.size.width,
self.bounds.origin.y,
3 * self.bounds.size.width,
self.bounds.size.height);
}
- 动画
-(void)didMoveToWindow {
[super didMoveToWindow];
[self.layer addSublayer:self.gradientLayer];
CABasicAnimation *gradientAnimation = [CABasicAnimation animationWithKeyPath:@"locations"];
gradientAnimation.fromValue = @[@0.0, @0.0, @0.25];
gradientAnimation.toValue = @[@.75,@1.,@1.];
//Challenges
// gradientAnimation.fromValue = @[@0.0, @0.0,@0.0, @0.0,@0.0, @0.0, @0.25];
// gradientAnimation.toValue = @[@0.65, @0.8, @0.85, @0.9, @0.95,@1.];
gradientAnimation.duration = 3.;
gradientAnimation.repeatCount = INFINITY;
[self.gradientLayer addAnimation:gradientAnimation forKey:nil];
}
现在运行下你的程序应该长已经有这个效果了

+ 接下来添加文字
原理就是一个文字图片作为mask层遮罩在刚才的gradientLayer上。
我这里是在storyboard上添加一个属性
@property(nonatomic,copy)IBInspectable NSString *text;
添加后storyboard就会多一个属性

接下来使用截屏的方法生成一个image,吧这个image当做mask的内容
-(void)setText:(NSString *)text {
_text = text;
[self setNeedsDisplay];
UIGraphicsBeginImageContext(self.frame.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
[_text drawInRect:self.bounds withAttributes:self.textAttributes];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// test
// UIImageView *imageView = [[UIImageView alloc]init];
// imageView.image = image;
// imageView.frame = self.bounds;
// [self addSubview:imageView];
CALayer *maskLayer = [CALayer layer];
maskLayer.backgroundColor = [UIColor clearColor].CGColor;
maskLayer.frame = CGRectMake(self.bounds.size.width, 0, self.bounds.size.width, self.bounds.size.height);
maskLayer.contents = (__bridge id _Nullable)(image.CGImage);
self.gradientLayer.mask = maskLayer;
}
你在测试的时候可以打开test这段代码,看你的截图到底有没有添加上文字。再次运行工程,就已经达到一开始的效果了。要是你还是不满意可以打开change的代码使你的动画色彩更多。

点击这里可以查看[源码](https://github.com/aizexin/AIAnimationDemo)第26个cell,喜欢的给个star