iOS 广告倒计时的转圈动画

一个小而简单的动画,项目中是用来广告倒计时的,简单封装了一下,圆圈的大小、颜色以及倒计时时间等都可以自行设定。

先上效果图,demo 地址在最底部:
广告倒计时
使用起来很简单,只需以下三行代码
    QQCircleLoaderView *loaderView = [[QQCircleLoaderView alloc] initWithFrame:CGRectMake(100, 500, 80, 80)];
    loaderView.progress = 3;
    [self.view addSubview:loaderView];

核心代码如下:

自定义一个继承自 CALayer 的类,绘制圆环形状,并将它的属性 progress 暴露在外面以供其它类调用:
@interface QQCircleProgressLayer : CALayer

@property (nonatomic, assign) CGFloat progress;

@end

@implementation QQCircleProgressLayer

- (void)drawInContext:(CGContextRef)ctx {
    CGFloat radius = self.bounds.size.width / 2;
    CGFloat lineWidth = 4.0;
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(radius, radius) radius:radius - lineWidth / 2 startAngle:0.f endAngle:M_PI * 2 * self.progress clockwise:YES];
    // 颜色
    CGContextSetRGBStrokeColor(ctx, 253/255.0, 117/255.0, 17/255.0, 1);
    // 线条宽度
    CGContextSetLineWidth(ctx, 4.0);
    CGContextAddPath(ctx, path.CGPath);
    CGContextStrokePath(ctx);
}

- (instancetype)initWithLayer:(QQCircleProgressLayer *)layer {
    if (self = [super initWithLayer:layer]) {
        self.progress = layer.progress;
    }
    return self;
}

+ (BOOL)needsDisplayForKey:(NSString *)key {
    if ([key isEqualToString:@"progress"]) {
        return YES;
    }
    return [super needsDisplayForKey:key];
}

@end
初始化自定义的 CALayer ,触发动画:
   CABasicAnimation *ani = [CABasicAnimation animationWithKeyPath:@"progress"];
   ani.duration = progress;
   ani.toValue = @(1);
   ani.removedOnCompletion = YES;
   ani.fillMode = kCAFillModeForwards;
   [self.circleProgressLayer addAnimation:ani forKey:@"progressAni"];
动画完成后给 QQCircleLoaderView 添加个缩放动画:
    CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scaleAnimation.fromValue = [NSNumber numberWithFloat:fromValue];
    scaleAnimation.toValue = [NSNumber numberWithFloat:toValue];
    scaleAnimation.duration = interval;
    scaleAnimation.repeatCount = repeatCount;
    scaleAnimation.autoreverses = YES;
    scaleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [layer addAnimation:scaleAnimation forKey:nil];

代码比较简单,不过多叙述,有兴趣的可以直接看代码。

demo地址

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。