之前开到很多环形进度条,看上去很酷,然后就试着学习他们的代码,结果发现实现一个环形进度条一点也不简单。我就在想一个简单的进度条有这么复杂吗?
自己摸索后,有一个简单的实现方法。具体代码点击打开链接
自定义一个HXProgressView,在.m 中实现drawRect方法
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// 获取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 设置线宽
CGContextSetLineWidth(ctx, 5);
CGPoint centerPoint = self.center;//设置圆心位置
CGFloat radius = 90;// 设置半径
CGFloat startA = - M_PI_2;// 设置圆的起始位置
CGFloat endA = - M_PI_2 + M_PI * 2 * _progress;// 设置圆的终止位置
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:centerPoint
radius:radius
startAngle:startA
endAngle:endA
clockwise:YES];// 构建圆形
// 将路径添加到上下文
CGContextAddPath(ctx, path.CGPath);
CGContextStrokePath(ctx);
}
当我们传入进度值的时候,要不断画路径,即调用drawRect方法,但是该方法不推荐显示调用,系统提供了另外一个方法来调用该方法
[self setNeedsDisplay];
给视图添加一个Slider控件,做传值(进度值)使用,slider方法如下:
- (IBAction)sliderAction:(UISlider *)sender {
_progress = sender.value;
[self setNeedsDisplay];
}
这样就简单的实现了一个环形进度条。