实现一个如下的动画:
实现如果的动画方式大概有两种:
1.直接找一个GIF图片进行播放(最直接)
2.自己用代码绘制然后加上动画
第一种方式参考:播放GIF的几种方式
下面主要说一下第二种方式
代码主要用到:
CALayer+UIBezierPath+CAShapeLayer+CAGradientLayer+CABasicAnimation
1.创建一个图层
_layer = [CALayer layer];
_layer.frame = CGRectMake(100, 100, 110, 110);
_layer.backgroundColor = [UIColor blueColor].CGColor;
效果如下:
2.绘制一个路径,再生成一个背景圆环加到view上
//创建圆环
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(55, 55) radius:50 startAngle:0 endAngle:M_PI * 2 clockwise:YES];
//圆环遮罩
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.fillColor = [UIColor clearColor].CGColor;
shapeLayer.strokeColor = [UIColor whiteColor].CGColor;
shapeLayer.lineWidth = 5;
shapeLayer.strokeStart = 0;
shapeLayer.strokeEnd = 1;
shapeLayer.lineCap = kCALineCapRound;
shapeLayer.lineDashPhase = 0.8;
shapeLayer.path = bezierPath.CGPath;
[_layer setMask:shapeLayer];
效果如下:
3.利用CAGradientLayer绘制渐变的颜色
由于CAGradientLayer是坐标到坐标之间的渐变,需要什么效果需要自己定制
渐变成坐标如下:
//颜色渐变
NSMutableArray *colors = [NSMutableArray arrayWithObjects:(id)[UIColor blueColor].CGColor,(id)[RYUIColorWithRGB(255, 255, 255, 0.5) CGColor], nil];
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.shadowPath = bezierPath.CGPath;
gradientLayer.frame = CGRectMake(0, 0, 110, 55);
gradientLayer.startPoint = CGPointMake(1, 0);
gradientLayer.endPoint = CGPointMake(0, 0);
[gradientLayer setColors:[NSArray arrayWithArray:colors]];
NSMutableArray *colors1 = [NSMutableArray arrayWithObjects:(id)[RYUIColorWithRGB(255, 255, 255, 0.5) CGColor],(id)[[UIColor whiteColor] CGColor], nil];
CAGradientLayer *gradientLayer1 = [CAGradientLayer layer];
gradientLayer1.shadowPath = bezierPath.CGPath;
gradientLayer1.frame = CGRectMake(0, 55, 110, 55);
gradientLayer1.startPoint = CGPointMake(0, 1);
gradientLayer1.endPoint = CGPointMake(1, 1);
[gradientLayer1 setColors:[NSArray arrayWithArray:colors1]];
[_layer addSublayer:gradientLayer]; //设置颜色渐变
[_layer addSublayer:gradientLayer1];
效果如下
最后效果图如下
4.利用CABasicAnimation实现简单的旋转
- (void)animation {
//动画
CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotationAnimation.fromValue = [NSNumber numberWithFloat:0];
rotationAnimation.toValue = [NSNumber numberWithFloat:2.0*M_PI];
rotationAnimation.repeatCount = MAXFLOAT;
rotationAnimation.duration = 1;
rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[_layer addAnimation:rotationAnimation forKey:@"rotationAnnimation"];
}
这样我们就简单实现了圆形渐变旋转圆环.
我们可以根据需求设置不同的颜色,在开发中我是由白色到无色本来利用whiteColor到clearColor发现底色会变灰可能clear颜色比较特殊,后来只好根据alpha来改变.
参考资料:
iOS弧形渐变进度条原理实现分析
CAGradientLayer讲解
iOS 环形渐变进度条实现
iOS Core Animation 更加细致讲解