也做一会标题党, 实际内容还是很简单的, 就是普通的layer层动画, 唯一要注意的就是用到了
CALayer
的contents
, 好吧, 言归正传, 就说下如何实现炫酷倒计时光圈.
上面这个就是需求啦, 对于vip用户, 发言的倒计时光圈和普通人的不一样, 下面的是普通人的效果
对于普通的效果, 就是对一个圆环做动画, 动画的代码如下
CGFloat maxWidth = self.frame.size.width < self.frame.size.height ? self.frame.size.width : self.frame.size.height;
CGPoint center = CGPointMake(maxWidth / 2.0, maxWidth / 2.0);
CGFloat radius = maxWidth / 2.0;
UIBezierPath *progressPath = [UIBezierPath bezierPathWithArcCenter:center
radius:radius - 2
startAngle:-M_PI_2
endAngle:3 * M_PI_2
clockwise:YES];
progressPath.lineCapStyle = kCGLineCapRound;
self.progressShapeLayer.path = progressPath.CGPath;
_progressAnimation = [CABasicAnimation animationWithKeyPath:@"strokeStart"];
self.progressAnimation.duration = time;
self.progressAnimation.fromValue = @(0);
self.progressAnimation.toValue = @(1);
self.progressAnimation.delegate = self;
self.progressAnimation.removedOnCompletion = NO;
self.progressAnimation.fillMode = kCAFillModeForwards;
[self.progressAnimation setValue:@"progressAnimation" forKey:@"key"];
[self.progressShapeLayer addAnimation:self.progressAnimation forKey:@"progressAnimation"];
就是对strokeStart
做动画, 起始位置是-M_PI_2
, 结束为止是3 * M_PI_2
, 至于CABasicAnimation
里面的参数这里就不过多的解释了, 请参照苹果官方的说明吧, 这里下面重点说下VIP的效果.
初始化
- (void)initViews {
_gradientLayer = [CALayer layer];
self.gradientLayer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"发言框"].CGImage);
_progressShapeLayer = [CAShapeLayer new];
self.progressShapeLayer.fillColor = [UIColor clearColor].CGColor;
self.progressShapeLayer.lineCap = kCALineCapRound;
self.progressShapeLayer.strokeColor = [UIColor colorWithValue:0x00eaff].CGColor;
self.progressShapeLayer.lineWidth = 2;
self.backgroundColor = [UIColor clearColor];
}
添加mask
- (void)startAnimationWithTime:(int64_t)time remindTime:(float)remindTime
{
if (self.progressAnimation) {
return;
}
[self.gradientLayer setMask:self.progressShapeLayer];
[self.layer addSublayer:self.gradientLayer];
}
startAnimationWithTime
是对外的接口, gradientLayer
相当于一个底图, 上面盖一个我们要做动画的层progressShapeLayer
, 实际做动画的还是progressShapeLayer
, 对于普通的底图, 就是个纯色的layer, mask是空的, 对progressShapeLayer
就行了, 然而对于有特殊要求的底图, 需要对mask做动画, 来影响底图. 有点绕, 大家看代码回味下吧.
代码已经整理出来放到git上了点我看demo