也做一會標題黨, 實際內容還是很簡單的, 就是普通的layer層動畫, 唯一要注意的就是用到了
CALayer
的contents
, 好吧, 言歸正傳, 就說下如何實現炫酷倒計時光圈.
VIP的效果圖
上面這個就是需求啦, 對于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