当需要显示数据的占比情况时,根据场景需要,写了个带动画效果的线形与圆形比例Demo,以供参考.
主要方法:
(1)线形图-使用简单animateWithDuration改变frame即可.
(2)圆形图有两种形式:
1.CABasicAnimation.
2.NSTimer改变圆形path的endAngle
一.主要代码
(1)线形图-显示比例动画
1.创建灰色背景与比例显示的view
//背景
bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
bgView.layer.borderColor = [UIColor clearColor].CGColor;
bgView.layer.borderWidth = 0.5;
bgView.layer.cornerRadius = self.frame.size.height/2;
[bgView.layer setMasksToBounds:YES];
bgView.clipsToBounds = YES;
[self addSubview:bgView];
//比例
scaleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.height/2, self.frame.size.height)];
scaleView.layer.borderColor = [UIColor clearColor].CGColor;
scaleView.layer.borderWidth = 0.5;
scaleView.layer.cornerRadius = self.frame.size.height/2;
[scaleView.layer setMasksToBounds:YES];
[self addSubview:scaleView];
2.drawRect方法中处理动画效果即可
[UIView animateWithDuration:1.8 animations:^{
scaleView.frame = CGRectMake(0, 0, self.frame.size.width*(self.currentValue/self.maxValue), self.frame.size.height);
}];
(2)圆形图-CABasicAnimation显示比例动画
//加入cashapelayer
CAShapeLayer *circleLayer = [CAShapeLayer layer];
circleLayer.path = scalePath.CGPath;
circleLayer.lineCap = kCALineCapRound;
circleLayer.lineWidth = 8;
circleLayer.frame = self.bounds;
circleLayer.fillColor = [UIColor clearColor].CGColor;
circleLayer.strokeColor = PNFreshGreen.CGColor;
[self.layer addSublayer:circleLayer];
//动画
CABasicAnimation *baseAnima = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
baseAnima.duration = 2.8;
baseAnima.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
baseAnima.delegate = self;
baseAnima.fromValue = [NSNumber numberWithInteger:0];
baseAnima.toValue = [NSNumber numberWithInteger:1];
[circleLayer addAnimation:baseAnima forKey:@"strokeEndAnimation"];
(3)圆形图-NSTimer显示比例动画
NSTimer执行方法,重绘改变圆形path的endAngle.
//2.显示比例动画 NSTimer形式
UIBezierPath *scalePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.bounds.size.width / 2,self.bounds.size.height / 2) radius:self.bounds.size.height / 2 - 9 / 2 startAngle:(CGFloat)-M_PI_2 endAngle:(CGFloat)(- M_PI_2 + self.animationTime * 2*M_PI) clockwise:YES];
UIColor *scaleColor = PNFreshGreen;
[scaleColor setStroke];
scalePath.lineWidth = 8;
[scalePath stroke];
- (void)NSTimerScaleAnimation{
self.animationTime = self.animationTime+0.003;
if (self.animationTime <= self.currentValue/self.maxValue) {
[self setNeedsDisplay];
}else{
[self.timer invalidate];
}
}
二.实现效果
(1)线形图-显示比例动画
(2)圆形图-CABasicAnimation显示比例动画
(3)圆形图-NSTimer显示比例动画
此处与CABasicAnimation显示区别在于:圆环端口形状.
四.Demo地址
欢迎star : https://github.com/FTC-Chen/LineAndCircleScaleView
有任何问题请私信或者留言,或者有更好的实现方法,也请告诉我.