進度條在iOS開發中很常見的,我在項目開發中也寫過好多進度條,有好多種類的,條形,圓形等,今天給大家總結一種圓形的開發進度條。自定義條形進度條
原理很簡單我就不說了,自己看代碼很容易理解,代碼也有注釋,直接上效果和代碼了。。
#######效果圖
1.gif
#######部分代碼
/** 畫板 */
- (void)drawRect:(CGRect)rect {
// 創建一個track shape layer
_trackLayer = [CAShapeLayer layer];
_trackLayer.frame = self.bounds;
_trackLayer.fillColor = [[UIColor clearColor] CGColor];
_trackLayer.strokeColor = [[UIColor cyanColor] CGColor];
[self.layer addSublayer:_trackLayer];
// 指定path的渲染顏色
_trackLayer.opacity = 1; // 背景透明度
_trackLayer.lineCap = kCALineCapRound;// 指定線的邊緣是圓的
_trackLayer.lineWidth = PROGRESS_LINE_WIDTH; // 線的寬度
// 上面說明過了用來構建圓形
/*
center:圓心的坐標
radius:半徑
startAngle:起始的弧度
endAngle:圓弧結束的弧度
clockwise:YES為順時針,No為逆時針
方法里面主要是理解startAngle與endAngle
*/
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.frame.size.width/2, self.frame.size.height/2)
radius:self.frame.size.width/2
startAngle:degreesToRadians(270)
endAngle:degreesToRadians(-90) clockwise:NO];
_trackLayer.path = [path CGPath]; // 把path傳遞給layer,然后layer會處理相應的渲染,整個邏輯和CoreGraph是一致的。
_progressLayer = [CAShapeLayer layer];
_progressLayer.frame = self.bounds;
_progressLayer.fillColor = [[UIColor clearColor] CGColor];
_progressLayer.strokeColor = [[UIColor redColor] CGColor];
_progressLayer.lineCap = kCALineCapRound;
_progressLayer.lineWidth = PROGRESS_LINE_WIDTH;
_progressLayer.path = [path CGPath];
_progressLayer.opacity = 1;
_progressLayer.strokeEnd = 0;
[self.layer addSublayer:_progressLayer];
}
-(instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
self.backgroundColor = [UIColor clearColor];
[self setUpSubViews];
}
return self;
}
- (void)setUpSubViews{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, (self.frame.size.height-20)/2, self.frame.size.width, 20)];
label.textColor = [UIColor blueColor];
label.textAlignment =1;
self.lable = label;
[self addSubview:label];
}
-(void)CircularProgressViewStart{
if (self.timer == nil) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(ChangeCircleValue:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
});
}
}
-(void)ChangeCircleValue:(NSTimer *)timer{
if (self.progress >= self.signProgress){
[self.timer invalidate];
self.timer = nil;
return;
}
self.progress += 0.01;
self.lable.text = [NSString stringWithFormat:@"%.1f%",self.progress * 100];
_progressLayer.strokeEnd = self.progress;
}
2016年09月26日 未完待續。。 有什么問題可以提出意見。。自定義圓形進度條GitHubDemo