[Demo下載]
(https://git.oschina.net/remainedmute/CircleProgressDemo.git)
廢話不多,先上效果圖

效果圖.gif
![Uploading 大圖瀏覽_874905.gif . . .]
看完效果,來看代碼
1.主要原理:在drawRect方法中實(shí)現(xiàn)如下方法
//An opaque type that represents a Quartz 2D drawing environment.
//一個(gè)不透明類型的Quartz 2D繪畫環(huán)境,相當(dāng)于一個(gè)畫布,你可以在上面任意繪畫
CGContextRef context = UIGraphicsGetCurrentContext();
/*畫圓*/
//邊框圓 -- 底色
UIColor *aColor = _cusBackgroundColor;
if (!aColor) aColor = [UIColor colorWithRed:78/255.0 green:77/255.0 blue:77/255.0 alpha:1];
CGContextSetStrokeColorWithColor(context, aColor.CGColor); //畫筆線的顏色
CGContextSetLineWidth(context, lineWidth);//線的寬度
CGContextAddArc(context, centerX, centerY, radius, 2*PI*(bgsAngle/360.0),8*PI*(bgeAngle/360.0), NO); // 添加一個(gè)圓
CGContextDrawPath(context, kCGPathStroke); // 繪制路徑
//邊框圓 -- 前景色
UIColor *bColor = _foregroundColor;
if (!bColor) bColor = [UIColor colorWithRed:27/255.0 green:158/255.0 blue:255/255.0 alpha:1];
CGContextSetStrokeColorWithColor(context, bColor.CGColor); //畫筆線的顏色
CGContextSetLineWidth(context, lineWidth);//線的寬度
//void CGContextAddArc(CGContextRef c,CGFloat x, CGFloat y,CGFloat radius,CGFloat startAngle,CGFloat endAngle, int clockwise)1弧度=180°/π (≈57.3°) 度=弧度×180°/π 360°=360×π/180 =2π 弧度
// x,y為圓點(diǎn)坐標(biāo),radius半徑,startAngle為開始的弧度,endAngle為 結(jié)束的弧度,clockwise 0為順時(shí)針,1為逆時(shí)針。
CGContextAddArc(context, centerX, centerY, radius, 2*PI*(_startAngle/360.0), 2*PI*(_endAngle/360), NO); // 添加一個(gè)圓
CGContextDrawPath(context, kCGPathStroke); // 繪制路徑
2.設(shè)置每次的進(jìn)度間隔為2,通過設(shè)置的起始角度,計(jì)算出需要循環(huán)的次數(shù),然后不斷刷新UI
- (void)doSomething {
// 獲取循環(huán)次數(shù)
int count = (_animCountAngle - _startAngle)/2 + 1;
if (count <= 0) count = 1;
// 定義時(shí)間間隔
CGFloat timeSlot = _animTime * 1.0/count; // 每一度停止時(shí)間
if (timeSlot < 0) timeSlot = 0;
// 獲取角度間隔
int angleSlot = 2;
// 獲取百分比間隔
CGFloat ratioSlot = 0;
if (_animRatio != nil) ratioSlot = [_animRatio floatValue]* 1.0/count;
@synchronized(self) {
// 循環(huán)更新UI
for (int i = 0; i <= count; i++) {
// 設(shè)置顯示的角度
_endAngle = _startAngle + i * angleSlot;
if (_endAngle > _animCountAngle) _endAngle = _animCountAngle;
// 設(shè)置
if (_animRatio != nil) _ratio = [NSString stringWithFormat:@"%.2f",(float)(0 + i * ratioSlot)];
else _ratio = nil;
[self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO];
if (self.animation) {
[NSThread sleepForTimeInterval:timeSlot];
}
}
}
}
3.值得注意的是,上面的方法中用到了@synchronized關(guān)鍵字,主要是因?yàn)楫?dāng)我們將這個(gè)view放在UITableViewCell里的時(shí)候,然后對(duì)UITableView進(jìn)行不斷刷新會(huì)出現(xiàn)閃退現(xiàn)象,經(jīng)過排查是for循環(huán)處線程問題,所以對(duì)for循環(huán)加了線程互斥鎖@synchronized。