一個(gè)小而簡(jiǎn)單的動(dòng)畫仍稀,項(xiàng)目中是用來(lái)廣告倒計(jì)時(shí)的拳芙,簡(jiǎn)單封裝了一下察藐,圓圈的大小、顏色以及倒計(jì)時(shí)時(shí)間等都可以自行設(shè)定舟扎。
先上效果圖分飞,demo 地址在最底部:
廣告倒計(jì)時(shí)
使用起來(lái)很簡(jiǎn)單,只需以下三行代碼
QQCircleLoaderView *loaderView = [[QQCircleLoaderView alloc] initWithFrame:CGRectMake(100, 500, 80, 80)];
loaderView.progress = 3;
[self.view addSubview:loaderView];
核心代碼如下:
自定義一個(gè)繼承自 CALayer 的類睹限,繪制圓環(huán)形狀譬猫,并將它的屬性 progress 暴露在外面以供其它類調(diào)用:
@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 ,觸發(fā)動(dòng)畫:
CABasicAnimation *ani = [CABasicAnimation animationWithKeyPath:@"progress"];
ani.duration = progress;
ani.toValue = @(1);
ani.removedOnCompletion = YES;
ani.fillMode = kCAFillModeForwards;
[self.circleProgressLayer addAnimation:ani forKey:@"progressAni"];
動(dòng)畫完成后給 QQCircleLoaderView 添加個(gè)縮放動(dòng)畫:
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];
代碼比較簡(jiǎn)單羡疗,不過(guò)多敘述染服,有興趣的可以直接看代碼。