在项目开发阶段,很多时候用到下载、或者加载数据,加载界面大部分用的是MBProgressHUD,但是有的时候想自定义一个下载进度或者是家在进度,那么该怎么实现呢?苹果给了一个很强大的库------Quartz2D,使用贝塞尔曲线自己去画,很方便,做一些DIY效果,很炫酷,我这里做了一个简单的DEMO,只是让大家熟悉一下怎么用,工程里用的时候还需要好好封装一下;
少说废话上代码:
先建一个TestView
TestView.h
#import <UIKit/UIKit.h>
@interface TestView : UIView
/**
* 调节进度的参数
*/
@property (nonatomic,assign) CGFloat progress;
@end
TestView.m
#import "TestView.h"
@interface TestView()
/**
* 现实加载的进度
*/
@property (nonatomic,strong) UILabel *label;
@end
@implementation TestView
/**
* 懒加载一个现实加载进度的label
*
* @return label
*/
- (UILabel *)label
{
if (!_label)
{
//这些代码对于你们来说:简单的跟一似的。
_label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0,100 , 60)];
_label.textAlignment = NSTextAlignmentCenter;
[self addSubview:_label];
_label.center = CGPointMake(50, 50);
}
return _label;
}
/**
* 重写进度参数的set方法
*
* @param progress 加载进度
*/
- (void)setProgress:(CGFloat)progress
{
_progress = progress;
self.label.text = [NSString stringWithFormat:@"%.2f%%",progress * 100];
//这里需要display,否则画的图没有渲染;
[self setNeedsDisplay];
}
/**
* 画图
*
* @param rect rect
*/
- (void)drawRect:(CGRect)rect {
//创建上下文
CGContextRef tex = UIGraphicsGetCurrentContext();
//拼接路径
CGPoint center = CGPointMake(50, 50);
//半径
CGFloat radius = 48;
//起始点
CGFloat startA = -M_PI_2;
//相当于重点
CGFloat startB = -M_PI_2 + _progress * M_PI * 2;
//使用贝塞尔曲线画图
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:startB clockwise:YES];
//添加到上下文
CGContextAddPath(tex, path.CGPath);
//把上下文渲染到视图
CGContextStrokePath(tex);
}
@end
使用方法,我是在storyBoard上面拖的,然后拖一个slider,用来模拟加载数据;
ViewController.m
#import "ViewController.h"
#import "TestView.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet TestView *progress;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)valueChange:(id)sender {
_progress.progress = [(UISlider *)sender value];
}
@end
最后运行效果如下图:
如果转载请注明转于:AirZilong的博客