说明:动画只是一个对layer的过程按帧显示,事实上frame是一次变化的
原理:使用UIBezierPath创建路径(一个整圆)+CAShapeLayer的strokeEnd属性 (结束点+动画)-->得到动画画圈效果
1、属性说明
CAShapeLayer.h
@property CGFloat strokeStart;//画圈起点,默认0,支持动画
@property CGFloat strokeEnd;//画圈结束点,默认1,支持动画
2、代码部分(属性显示:不带动画)
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.frame = _demoView.bounds;
shapeLayer.strokeEnd = 0.7f;//结束点
shapeLayer.strokeStart = 0.1f;//开始点
//得到路径
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:_demoView.bounds];
shapeLayer.path = path.CGPath;
shapeLayer.fillColor = [UIColor clearColor].CGColor; //Layer 的填充色
shapeLayer.lineWidth = 2.0f;//宽度
shapeLayer.strokeColor = [UIColor redColor].CGColor;//边框色
//将CAShaperLayer放到某个层上显示
[_demoView.layer addSublayer:shapeLayer];
我们通过以上代码设置:strokeStart=0.1f; strokeEnd=0.7f
3、实现圆形进度条的实现代码(动画)
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.frame = _demoView.bounds;
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:_demoView.bounds];
shapeLayer.path = path.CGPath;
shapeLayer.fillColor = [UIColor clearColor].CGColor;//Layer 的填充色
shapeLayer.lineWidth = 2.0f;//宽度
shapeLayer.strokeColor = [UIColor redColor].CGColor;//边框色
[_demoView.layer addSublayer:shapeLayer];
CABasicAnimation *pathAnima = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnima.duration = 3.0f;//动画时间
pathAnima.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
pathAnima.fromValue = [NSNumber numberWithFloat:0.0f];//开始点
pathAnima.toValue = [NSNumber numberWithFloat:1.0f];//结束点
pathAnima.fillMode = kCAFillModeForwards;
pathAnima.removedOnCompletion = NO;
[shapeLayer addAnimation:pathAnima forKey:@"strokeEndAnimation"];
我们通过以上代码设置:strokeStart=0.1f; strokeEnd=1.0f,带动画效果
CABasicAnimation的“转圈”动画
1、确定动画轨迹
CGFloat w = CGRectGetWidth(frame);
CGFloat h = CGRectGetHeight(frame);
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(w/2, h/2)radius:MIN(w, h)/2 startAngle:-M_PI_2 endAngle:3 * M_PI_2 clockwise:YES];
2、创建动画
// 倒计时的时间
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeStart"];
animation.duration = 3;
animation.fromValue = @(0.f);
animation.toValue = @(1.f);
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeBoth;
3、CAShapeLayer添加动画
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.fillColor = [UIColor clearColor].CGColor;
shapeLayer.strokeColor = [UIColor colorWithRed:0.02f green:0.69f blue:1.00f alpha:1.00f].CGColor;
shapeLayer.lineWidth = 1.0;
[self.layer addSublayer:shapeLayer];
shapeLayer.path = path.CGPath;
[shapeLayer addAnimation:animation forKey:nil];
CABasicAnimation使用总结,UIBezierPath介绍, CAAnimation——基本动画,关键帧动画和贝塞尔路径
学无止境,做个记录
2017-01-12-SXH