鉴于之前那篇关于进度条的文章有点繁琐,利用了扇形和遮盖,比较麻烦,现在以另一种方法-贝塞尔曲线画进度条
直接代码
#import <UIKit/UIKit.h>
@interface test : UIView
@property(nonatomic, assign)float progressRate;
@property(nonatomic, strong)UIColor *color;
@property(nonatomic, assign)float x;
@property(nonatomic, assign)float y;
@property(nonatomic, assign)float radius;
@property(nonatomic, assign)float startAngle;
-(void)animateProgress:(float)progress animate:(BOOL)animate;
@end
#import "test.h"
#import <QuartzCore/QuartzCore.h>
@interface test()
@property(nonatomic,assign) float step;
@property(nonatomic,assign) float total;
@end
@implementation test
-(void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGPoint point = CGPointMake(_x, _y);
CGFloat endAngle = self.startAngle+2*M_PI*self.progressRate;
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithArcCenter:point radius:self.radius startAngle:self.startAngle endAngle:endAngle clockwise:YES];
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, 10.0);
CGContextSetStrokeColorWithColor(context, [UIColor purpleColor].CGColor);
CGContextAddPath(context, bezierPath.CGPath);
CGContextStrokePath(context);
}
-(void)animateProgress:(float)progress animate:(BOOL)animate
{
if (animate) {
self.total = progress;
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.01
target:self
selector:@selector(numberAnimation:)
userInfo:nil
repeats:YES];
}else{
[self setNeedsDisplay];
}
}
-(void)numberAnimation:(NSTimer*)timer
{
_step += 0.01;
if (self.step > self.total) {
[timer invalidate];
timer = nil;
self.step = 0;
return;
}
self.progressRate = self.step;
[self setNeedsDisplay];
}
@end
调用
#import "ViewController.h"
#import "test.h"
@interface ViewController ()
@property(nonatomic,strong) test *progressView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_progressView = [[test alloc]initWithFrame:CGRectMake(100, 200, 100, 100)];
self.progressView.x = 50;
self.progressView.y = 50;
self.progressView.radius = 40;
self.progressView.backgroundColor = [UIColor yellowColor];
[self.view addSubview:self.progressView];
}
- (IBAction)tapProgress:(id)sender {
[self.progressView animateProgress:0.8 animate:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}