效果

由于是demo我們這個直接拖拽xib實現(xiàn)布局

- 首先我們?yōu)樘匦н@個視圖單獨建一個
AIAnimationMaskLabel關聯(lián)起來
- 接下來配置
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;
現(xiàn)在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];
}
現(xiàn)在運行下你的程序應該長已經有這個效果了

+ 接下來添加文字
原理就是一個文字圖片作為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