所有复杂动画都是由简单动画组合而成的
swift和oc demo
动画细节拆分:
- 1.使用CAGradientLayer处理颜色渐变
-(CAGradientLayer *)gradientLayer{
if (!_gradientLayer) {
_gradientLayer = [CAGradientLayer layer];
_gradientLayer.frame = CGRectMake(-self.bounds.size.width, self.bounds.origin.y, 3
* self.bounds.size.width, self.bounds.size.height);
_gradientLayer.startPoint = CGPointMake(0, 0.5);
_gradientLayer.endPoint = CGPointMake(1.0, 0.5);
_gradientLayer.colors = @[
(__bridge id)[UIColor blackColor].CGColor,
(__bridge id)[UIColor whiteColor].CGColor,
(__bridge id)[UIColor blackColor].CGColor
];
_gradientLayer.locations = @[@0.25,@0.5,@0.75];
}
return _gradientLayer;
}
- 2.使用CABasicAnimation为CAGradientLayer添加动画
//添加动画
-(void)animationWithGradientLayer{
CABasicAnimation *gradientAnimation = [CABasicAnimation animationWithKeyPath:@"locations"];
gradientAnimation.fromValue = @[@0.0,@0.0,@0.25];
gradientAnimation.toValue = @[@0.75,@1.0,@1.0];
gradientAnimation.duration = 3.0;
gradientAnimation.repeatCount = MAXFLOAT;
[self.gradientLayer addAnimation:gradientAnimation forKey:nil];
}
- 3.将文字生成图片,设置gradientLayer的mask属性为图片,裁剪掉文字以外的部分
//文字生成图片
UIGraphicsBeginImageContext(self.bounds.size);
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSForegroundColorAttributeName] = [UIColor redColor];
dict[NSFontAttributeName] = [UIFont systemFontOfSize:30.0];
[_text drawInRect:self.bounds withAttributes:@{NSForegroundColorAttributeName: [UIColor redColor],NSFontAttributeName:[UIFont systemFontOfSize:30.0]}];
CGContextRef context= UIGraphicsGetCurrentContext ();
CGContextDrawPath (context, kCGPathStroke );
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
CALayer *maskLayer = [CALayer layer];
maskLayer.backgroundColor = [UIColor clearColor].CGColor;
maskLayer.frame = CGRectOffset(self.bounds, self.bounds.size.width, 0);
maskLayer.contents = (__bridge id _Nullable)(image.CGImage);
//使用蒙版裁剪掉没用的区域
self.gradientLayer.mask = maskLayer;