美文网首页
使用CALayer做加载或者刷新动画

使用CALayer做加载或者刷新动画

作者: __阳阳 | 来源:发表于2018-03-28 12:55 被阅读0次

    最近项目中的需求,拿出来记录一下,先看效果图:


    效果图.gif

    分析:这个动画其实只有两端弧L1和L2,动画过程就是L1的起点到L2的终点,L1的终点到L2的起点,L2的起点到L1的终点,L2的终点到L1的起点,L1和L2增量是一样的,这样就简单了。

    然后写一个继承自CALayer的类,然后写两个参数,使用这两个参数来控制L1和L2的起点和终点,然后我们对着两个参数做动画,然后动画就可以实现了

    思路说完了,开始上代码,这是layer里边的全部代码:

    @interface N_refreshLayer : CALayer
    // 开始绘制点增量 取值范围 0 - 1
    @property (nonatomic, assign) CGFloat startPross;
    // 结束绘制点增量 取值范围 0 - 1
    @property (nonatomic, assign) CGFloat endPross;
    // 这个用来控制layer的透明度(项目需求,没有需求可以不要)
    @property (nonatomic, assign) CGFloat lineAlpha;
    
    @end
    
    @implementation N_refreshLayer
    
    // 重写系统方法,当key为startPross或者endPross的时候进行重新绘制
    + (BOOL)needsDisplayForKey:(NSString *)key {
        if ([key isEqualToString:@"startPross"] || [key isEqualToString:@"endPross"]) {
            return YES;
        }
        return [super needsDisplayForKey:key];
    }
    
    // 重写系统方法,绘制圆弧
    - (void)drawInContext:(CGContextRef)ctx {
        
        // 这里边 - 1 是减去线宽的一半, - 6 是弧距离边界的距离
        CGFloat radius = MIN(CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds)) / 2 - 1 - 6;
        CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
        // L1
        UIBezierPath *path1 = [UIBezierPath bezierPath];
        // 这里说一下,顺时针角度为正,逆时针角度为负,我在-90°处开始绘制,后边M_PI*0.05是两条弧之间的间隔,最后边2*M_PI*参数,是控制增量的(M_PI是180°)
        CGFloat startAngle1= -M_PI_2 + M_PI*0.05- 2*M_PI*self.startPross;
        CGFloat endAngle1 = -M_PI_2 - M_PI*0.05 - 2*M_PI*self.endPross;
        [path1 addArcWithCenter:center radius:radius startAngle:startAngle1 endAngle:endAngle1 clockwise:NO];
        // L1    
        UIBezierPath *path2 = [UIBezierPath bezierPath];
        CGFloat startAngle2 = -M_PI_2 - M_PI*0.25 - 2*M_PI*self.endPross;
        CGFloat endAngle2 = -M_PI_2 + M_PI*0.25 - 2*M_PI*self.startPross;
        [path2 addArcWithCenter:center radius:radius startAngle:startAngle2 endAngle:endAngle2 clockwise:NO];
        
        CGContextAddPath(ctx, path1.CGPath);
        CGContextAddPath(ctx, path2.CGPath);
        CGContextSetLineWidth(ctx, 2);
        CGContextSetLineCap(ctx, kCGLineCapRound);
        CGContextSetStrokeColorWithColor(ctx, kRGBAColor(255, 0, 0, 1.0).CGColor);
        CGContextStrokePath(ctx);
    }
    
    - (void)setLineAlpha:(CGFloat)lineAlpha {
        self.opacity = lineAlpha;
    }
    
    

    然后在封装一个view将layer添加到view的layer上,在view里边控制layer的参数,view中的全部代码:

    // .h文件
    @interface N_RefreshAnimView : UIView
    // 提供几个控制动画的方法
    // 开始执行动画
    - (void)startAnimation;
    // 停止动画
    - (void)stopAnimation;
    // 设置增量(可以根据scrollView的偏移量来设置进度)
    - (void)setProgressWith:(CGFloat)progress;
    // 设置layer的透明度
    - (void)setLineAlphaWith:(CGFloat)lineAlpha;
    
    @end
    
    // .m文件
    @interface N_RefreshAnimView ()
    
    @property (nonatomic, strong) N_refreshLayer *animLayer;
    @property (nonatomic, strong) CABasicAnimation *anim1;
    @property (nonatomic, strong) CABasicAnimation *anim2;
    
    @end
    
    @implementation N_RefreshAnimView
    
    // 初始化方法
    - (instancetype)init {
        if (self = [super init]) {
            [self.layer addSublayer:self.animLayer];
        }
        return self;
    }
    
    - (instancetype)initWithFrame:(CGRect)frame {
        if (self = [super initWithFrame:frame]) {
            [self.layer addSublayer:self.animLayer];
        }
        return self;
    }
    
    - (instancetype)initWithCoder:(NSCoder *)aDecoder {
        if (self = [super initWithCoder:aDecoder]) {
            [self.layer addSublayer:self.animLayer];
        }
        return self;
    }
    
    - (void)startAnimation {
        CABasicAnimation *anim1 = (CABasicAnimation *)[self.animLayer animationForKey:@"anim1"];
        CABasicAnimation *anim2 = (CABasicAnimation *)[self.animLayer animationForKey:@"anim2"];
        // 如果layer上不存在动画,则进行添加动画
        if (!anim1) [self.animLayer addAnimation:self.anim1 forKey:@"anim1"];
        if (!anim2) [self.animLayer addAnimation:self.anim2 forKey:@"anim2"];
        // 如果存在动画则不继续执行
        if (anim1 && anim2 && self.animLayer.speed == 1) return;
        CFTimeInterval pauseTime = self.animLayer.timeOffset;
        CFTimeInterval begin = CACurrentMediaTime() - pauseTime;
        [self.animLayer setTimeOffset:0];
        [self.animLayer setBeginTime:begin];
        self.animLayer.speed = 1;
    }
    
    - (void)stopAnimation {
        // 设置layer的动画速度为0则停止动画
        CFTimeInterval pausedTime = [self.animLayer convertTime:CACurrentMediaTime() fromLayer:nil];
        self.animLayer.speed = 0.0;
        // 记录动画暂停的时间,在恢复动画的时候使用
        self.animLayer.timeOffset = pausedTime;
    }
    
    - (void)setProgressWith:(CGFloat)progress {
        [self.animLayer removeAllAnimations];
        self.animLayer.speed = 1.0;
        self.animLayer.startPross = progress * 0.15;
        self.animLayer.endPross = progress * 0.85;
        [self.animLayer setNeedsDisplay];
    }
    
    - (void)setLineAlphaWith:(CGFloat)lineAlpha {
        self.animLayer.lineAlpha = lineAlpha;
    }
    
    // 懒加载layer
    - (N_refreshLayer *)animLayer {
        if (!_animLayer) {
            _animLayer = [[N_refreshLayer alloc] init];
            _animLayer.startPross = 0.0;
            _animLayer.endPross = 0.0;
            [_animLayer setNeedsDisplay];
        }
        return _animLayer;
    }
    
    // 懒加载动画
    - (CABasicAnimation *)anim1 {
        if (!_anim1) {
            _anim1 = [CABasicAnimation animationWithKeyPath:@"startPross"];
            _anim1.removedOnCompletion = NO;
            _anim1.fillMode = kCAFillModeForwards;
            _anim1.repeatCount = MAXFLOAT;
            _anim1.duration = 0.8;
           // 动画1的增量加上动画2的增量为360°,增量与1之间差值的和为L1加间距的弧度 
            _anim1.toValue = [NSNumber numberWithFloat:0.15];
            _anim1.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
        }
        return _anim1;
    }
    
    - (CABasicAnimation *)anim2 {
        if (!_anim2) {
            _anim2 = [CABasicAnimation animationWithKeyPath:@"endPross"];
            _anim2.removedOnCompletion = NO;
            _anim2.fillMode = kCAFillModeForwards;
            _anim2.repeatCount = MAXFLOAT;
            _anim2.duration = 0.8;
           // 动画1的增量加上动画2的增量为360°,增量与1之间差值的和为L1加间距的弧度
            _anim2.toValue = [NSNumber numberWithFloat:0.85];
            _anim2.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
        }
        return _anim2;
    }
    
    - (void)layoutSubviews {
        [super layoutSubviews];
        self.animLayer.frame = self.bounds;
    }
    

    到此为止这个动画就可以使用了,细心的小伙伴会发现,这样画出来的线条会有锯齿,解决办法设置 _animLayer.contentsScale = [[UIScreen mainScreen] scale]; 就可以了,为了这个问题,浪费了我一下午时间,最后就TM一行代码

    下边是配合MJRefresh使用做下拉刷新,那么自定义MJRefresh,代码如下:

    .h文件
    #import <MJRefresh/MJRefresh.h>
    #import "N_RefreshAnimView.h"
    
    @interface N_RefreshHeader : MJRefreshHeader
    
    @end
    
    .m文件
    @interface N_RefreshHeader ()
    
    @property (nonatomic, strong) N_RefreshAnimView *animView;
    
    @end
    
    
    @implementation N_RefreshHeader
    
    - (void)prepare {
        [super prepare];
        [self addSubview:self.animView];
    }
    
    - (void)placeSubviews {
        [super placeSubviews];
        // 设置子控件位置
        self.animView.frame = CGRectMake(0, 0, 35, 35);
        self.animView.center = CGPointMake(self.mj_w/2.0, self.mj_h/2.0);
    }
    
    - (void)setState:(MJRefreshState)state {
        
        MJRefreshCheckState;
        
        switch (state) {
            case MJRefreshStateIdle:
                [self.animView stopAnimation];
                break;
            case MJRefreshStatePulling:
                break;
            case MJRefreshStateRefreshing:
                [self.animView startAnimation];
                break;
            default:
                break;
        }
    }
    
    - (void)setPullingPercent:(CGFloat)pullingPercent {
        // 控制layer的动画进度和透明度
        if (pullingPercent > 0) [self.animView setLineAlphaWith:pullingPercent];
        CGFloat progress = pullingPercent - (int)pullingPercent;
        [self.animView setProgressWith:progress];
    }
    
    - (void)endRefreshing {
        [super endRefreshing];
    }
    
    - (N_RefreshAnimView *)animView {
        if (!_animView) {
            _animView = [[N_RefreshAnimView alloc] init];
            _animView.backgroundColor = [UIColor whiteColor];
            // 这里我的需求需要圆形和阴影效果
            _animView.layer.cornerRadius = 17.5;
            _animView.layer.shadowColor = [UIColor blackColor].CGColor;
            _animView.layer.shadowOpacity = 0.1;
            _animView.layer.shadowOffset = CGSizeMake(3, 3);
            _animView.layer.shadowRadius = 5.0;
        }
        return _animView;
    }
    
    

    至此这个动画就完成了!有意见或者建议的小伙伴欢迎下边评论,批评或指正

    相关文章

      网友评论

          本文标题:使用CALayer做加载或者刷新动画

          本文链接:https://www.haomeiwen.com/subject/xwdycftx.html