CAGradientLayer渐变颜色动画
或许你用过CAGradientLayer,你知道他是用于渐变颜色的,但你是否直到,CAGradientLayer的渐变颜色是可以动画的哦.
源码:
// // RootViewController.m // CAGradientLayer // // Copyright (c) 2014年 Y.X. All rights reserved. // #import "RootViewController.h" #import "CAShapeLayer+Circle.h" #import "YXGCD.h" @interface RootViewController () @property (nonatomic, strong) GCDTimer *timer; @end @implementation RootViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor blackColor]; // 创建形状遮罩 CAShapeLayer *circleLayer = [CAShapeLayer LayerWithCircleCenter:CGPointMake(82, 82) radius:80 startAngle:DEGREES(0) endAngle:DEGREES(360) clockwise:YES lineDashPattern:@[@5, @5]]; circleLayer.strokeColor = [UIColor blackColor].CGColor; // 边缘线的颜色 circleLayer.lineCap = kCALineCapSquare; // 边缘线的类型 circleLayer.lineWidth = 1.0f; // 线条宽度 circleLayer.strokeStart = 0.0f; circleLayer.strokeEnd = 1.0f; // 创建渐变图层 CAGradientLayer *faucet = [CAGradientLayer layer]; faucet.frame = CGRectMake(0, 0, 200, 200); faucet.position = self.view.center; // 以CAShapeLayer的形状作为遮罩是实现特定颜色渐变的关键 faucet.mask = circleLayer; faucet.colors = @[(id)[UIColor greenColor].CGColor, (id)[UIColor redColor].CGColor, (id)[UIColor cyanColor].CGColor]; // 设定动画时间 faucet.speed = 0.5f; // 添加到系统图层中 [self.view.layer addSublayer:faucet]; // 定时器动画事件 _timer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]]; [_timer event:^{ circleLayer.strokeEnd = arc4random() % 100 / 100.f; faucet.colors = @[(id)[UIColor colorWithRed:arc4random()%255/255.f green:arc4random()%255/255.f blue:arc4random()%255/255.f alpha:1].CGColor, (id)[UIColor colorWithRed:arc4random()%255/255.f green:arc4random()%255/255.f blue:arc4random()%255/255.f alpha:1].CGColor, (id)[UIColor colorWithRed:arc4random()%255/255.f green:arc4random()%255/255.f blue:arc4random()%255/255.f alpha:1].CGColor, (id)[UIColor colorWithRed:arc4random()%255/255.f green:arc4random()%255/255.f blue:arc4random()%255/255.f alpha:1].CGColor, (id)[UIColor colorWithRed:arc4random()%255/255.f green:arc4random()%255/255.f blue:arc4random()%255/255.f alpha:1].CGColor]; } timeInterval:NSEC_PER_SEC]; [_timer start]; } @end
效果如下:
以下代码才是核心的地方:
附录:
http://*.com/questions/21121670/cagradientlayer-with-cashapelayer-mask-not-showing