第一次使用簡書,記錄下平時寫的demo,
因為最近時間比較閑,所以找了些網上的效果下載下來學習下,首先說明這是從別人那下載下來的,下載地址:http://download.csdn.net/download/u011918080/7632701
這個效果可以用來顯示當前的任務進度或者其他的效果,也可以用來進行計時,我是拿來計時的,
效果展示:點擊開始按鈕開始執行動畫,黃色是已經計時的時間,紅色是剩余時間,本來應該有個label來顯示時間的,也沒時間搞了
其實效果很簡單,代碼也容易,奈何以前沒接觸過畫圖之類的,算是一個小筆記吧,
思路:在一個view里面繪制一個背景圓,然后通過定時器來畫另一個圓,
代碼:
- (void)drawCircleWithRect:(CGRect)rect margin:(CGFloat)margin color:(UIColor *)color percentage:(CGFloat)percentage
{
CGContextRef context = UIGraphicsGetCurrentContext();
//設置半徑
CGFloat radius = MIN(CGRectGetHeight(rect), CGRectGetWidth(rect)) * 0.5 - margin;
//圓心
CGFloat centerX = CGRectGetWidth(rect) * 0.5;
CGFloat centerY = CGRectGetHeight(rect) * 0.5;
//設置起始角度
CGFloat startAngle = M_PI * 1.5;//從y軸正方向開始畫
//根據傳過來的百分比計算改變的角度的值
CGFloat changeAngle = M_PI * 2 * percentage;
//設置結束時的角度 改變的角度加上起始時的角度就是結束時的角度
CGFloat endAngle = changeAngle + startAngle;
//設置繪圖的起始點
CGContextMoveToPoint(context, centerX, centerY);
//畫圓
CGContextAddArc(context, centerX, centerY, radius, startAngle, endAngle, 0);
//設置圖形的顏色
CGContextSetFillColorWithColor(context, color.CGColor);
//閉合路徑
CGContextClosePath(context);
//填充路徑
CGContextFillPath(context);
}
添加定時器
- (void)start
{
if (!self.timer.isValid) {
if (_currentProgress < 0 || _currentProgress > 100) {
_currentProgress = 0.f;
}
//*0.01也就是1/100.self.totalTime * 0.01是因為在updateProgress方法里_currentProgress/100; time 默認10s是因為100*0.1等于10;
CGFloat time = self.totalTime ? self.totalTime * 0.01 : 0.1;
self.timer = [NSTimer scheduledTimerWithTimeInterval:time
target:self
selector:@selector(updateProgress)
userInfo:nil
repeats:YES];
[self.timer fire];
}
}
定時器方法
- (void)updateProgress {
if ([_delegate respondsToSelector:@selector(wyProgressViewWillUpdateProgress:percentage:)]) {
[_delegate wyProgressViewWillUpdateProgress:self percentage:_progress];
}
//計算當前的進度
_progress = _currentProgress++ / 100;
if (_progress >= 1) {
[self stop];
return;
}
//會自動調用drawRect方法
[self setNeedsDisplay];
if ([_delegate respondsToSelector:@selector(wyProgressViewDidUpdateProgress:percentage:)]) {
[_delegate wyProgressViewDidUpdateProgress:self percentage:_progress];
}
}
下載:自己的demo