一、CAShapeLayer后续
基于上一篇文章CAShapeLayer初探的要求,笔者会在这篇文章中简析动画进度圈的封装步骤和代码实现。封装思路很简单,没有多少的代码,新接触CAShapeLayer
的同志们可以看看哦。
先来一张运行后的效果图:
二、封装思路
1、有关类介绍
CAShapeLayer
渲染图层,UIBezierPath
绘制图层路径,CABasicAnimation
实现动画。
2、图层解析
效果图所看到的只有两层图层而已,一个是view层,显示圆的部分;一个是label层,显示百分比。
3、封装步骤
1)、创建CAShapeLayer
对象
- (CAShapeLayer *)shapeLayer
{
if (!_shapeLayer) {
_shapeLayer = [CAShapeLayer layer];
}
return _shapeLayer;
}
2)、创建UILabel
对象
- (UILabel *)precentLable
{
if (!_precentLable) {
_precentLable = [[UILabel alloc] init];
_precentLable.font = [UIFont systemFontOfSize:20.0 weight:5.0];
_precentLable.textColor = [UIColor orangeColor];
_precentLable.textAlignment = NSTextAlignmentCenter;
_precentLable.text = [NSString stringWithFormat:@"0%%"];
_precentLable.backgroundColor = [UIColor clearColor];
}
return _precentLable;
}
3)、重新布局子控件
- (void)layoutSubviews
{
[super layoutSubviews];
_shapeLayer.frame = self.bounds;
_precentLable.frame = CGRectMake(0, 0, self.frame.size.width, 30);
_precentLable.center = CGPointMake(self.center.x - self.frame.origin.x,self.center.y - self.frame.origin.y);
//设置圆心,半径,起始角与结束角
bezierPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.center.x - self.frame.origin.x,self.center.y - self.frame.origin.y) radius:self.frame.size.width/2 - radius startAngle:-M_PI_2 endAngle:-M_PI_2+M_PI*2 clockwise:YES];
// bezierPath = [UIBezierPath bezierPathWithOvalInRect:self.bounds];
_shapeLayer.path = bezierPath.CGPath;
_shapeLayer.lineWidth = lineWidth;
}
4)、开始动画
- (void)startAnimation
{
CGFloat precent = [_precent floatValue];
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
animation.duration = duration;
animation.fromValue = @(0);
animation.toValue = @(precent/100);
animation.speed = 2.0;
_shapeLayer.strokeStart = 0;
_shapeLayer.strokeEnd = precent/100;
//这个Key可以随便填
[_shapeLayer addAnimation:animation forKey:@"strokeEndAnimation"];
}