iOS开发-绘制iOS Developer

iOS开发之CAShapeLayer后续——动画进度圈

2017-09-11  本文已影响284人  施忆

一、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"];
}

三、Demo下载

demo

上一篇 下一篇

猜你喜欢

热点阅读