一、CAShapeLayer后續(xù)
基于上一篇文章CAShapeLayer初探的要求,筆者會在這篇文章中簡析動畫進度圈的封裝步驟和代碼實現(xiàn)。封裝思路很簡單,沒有多少的代碼,新接觸CAShapeLayer的同志們可以看看哦。
先來一張運行后的效果圖:

效果圖
二、封裝思路
1、有關類介紹
CAShapeLayer渲染圖層,UIBezierPath繪制圖層路徑,CABasicAnimation實現(xiàn)動畫。
2、圖層解析
效果圖所看到的只有兩層圖層而已,一個是view層,顯示圓的部分;一個是label層,顯示百分比。

圖層
3、封裝步驟
1)、創(chuàng)建CAShapeLayer對象
- (CAShapeLayer *)shapeLayer
{
if (!_shapeLayer) {
_shapeLayer = [CAShapeLayer layer];
}
return _shapeLayer;
}
2)、創(chuàng)建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"];
}