美文网首页
iOS - 扇形计时动画

iOS - 扇形计时动画

作者: 哆啦_ | 来源:发表于2016-05-05 17:38 被阅读510次

第一次使用简书,记录下平时写的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

相关文章

网友评论

      本文标题:iOS - 扇形计时动画

      本文链接:https://www.haomeiwen.com/subject/nisflttx.html