// // TBCycleView.h // TBCycleProgress //. // #import <UIKit/UIKit.h> @interface TBCycleView : UIView @property (nonatomic, strong) UILabel *label; - (void)drawProgress:(CGFloat )progress; @end
// // TBCycleView.m // TBCycleProgress // // #import "TBCycleView.h" @interface TBCycleView () @property (nonatomic, assign) CGFloat progress; @property (nonatomic, strong) CAShapeLayer *progressLayer; @end @implementation TBCycleView - (UILabel *)label { if (_label == nil) { UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; label.textAlignment = NSTextAlignmentCenter; label.center = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2); [self addSubview:label]; _label = label; } return _label; } - (void)drawProgress:(CGFloat )progress { _progress = progress; _progressLayer.opacity = 0; [self setNeedsDisplay]; } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { [self drawCycleProgress]; } - (void)drawCycleProgress { CGPoint center = CGPointMake(100, 100); CGFloat radius = 90; CGFloat startA = - M_PI_2; //設置進度條起點位置 CGFloat endA = -M_PI_2 + M_PI * 2 * _progress; //設置進度條終點位置 //獲取環形路徑(畫一個圓形,填充色透明,設置線框寬度爲10,這樣就得到了一個環形) _progressLayer = [CAShapeLayer layer];//建立一個track shape layer _progressLayer.frame = self.bounds; _progressLayer.fillColor = [[UIColor clearColor] CGColor]; //填充色爲無色 _progressLayer.strokeColor = [[UIColor redColor] CGColor]; //指定path的渲染顏色,這裏能夠設置任意不透明顏色 _progressLayer.opacity = 1; //背景顏色的透明度 _progressLayer.lineCap = kCALineCapRound;//指定線的邊緣是圓的 _progressLayer.lineWidth = 10;//線的寬度 UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];//上面說明過了用來構建圓形 _progressLayer.path =[path CGPath]; //把path傳遞給layer,而後layer會處理相應的渲染,整個邏輯和CoreGraph是一致的。 [self.layer addSublayer:_progressLayer]; //生成漸變色 CALayer *gradientLayer = [CALayer layer]; //左側漸變色 CAGradientLayer *leftLayer = [CAGradientLayer layer]; leftLayer.frame = CGRectMake(0, 0, self.bounds.size.width / 2, self.bounds.size.height); // 分段設置漸變色 leftLayer.locations = @[@0.3, @0.9, @1]; leftLayer.colors = @[(id)[UIColor yellowColor].CGColor, (id)[UIColor greenColor].CGColor]; [gradientLayer addSublayer:leftLayer]; //右側漸變色 CAGradientLayer *rightLayer = [CAGradientLayer layer]; rightLayer.frame = CGRectMake(self.bounds.size.width / 2, 0, self.bounds.size.width / 2, self.bounds.size.height); rightLayer.locations = @[@0.3, @0.9, @1]; rightLayer.colors = @[(id)[UIColor yellowColor].CGColor, (id)[UIColor redColor].CGColor]; [gradientLayer addSublayer:rightLayer]; [gradientLayer setMask:_progressLayer]; //用progressLayer來截取漸變層 [self.layer addSublayer:gradientLayer]; } @end