工程描述图:
角度描述图:
工程结构:
- ViewController中创建一个自定义视图UIView, 和一个UISlider控件, 实现拖动slider控制进度.
- 自定义UIView : 一个UILabel来显示进度 + 绘制弧度 根据slider的值, 来改变label的值和弧线的值
工程实现代码
ViewController.m文件
#import "ViewController.h"
#import "ProgressView.h"
@interface ViewController ()
@property(strong, nonatomic) ProgressView *pView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//设置自定义View
self.pView = [[ProgressView alloc] initWithFrame:CGRectMake(100, 230, self.view.frame.size.width - 200, 200)];
self.pView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:self.pView];
//设置Slider
UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(100, 100, 200, 30)];
slider.maximumValue = 1;
slider.minimumValue = 0;
//给slider添加事件
[slider addTarget:self action:@selector(slider:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:slider];
}
- (void)slider:(UISlider *)slider{
//将slider的值传递给View界面的属性, 用来控制自定View界面的label值和弧形的形状
_pView.progress = slider.value;
}
@end```
####ProgressView.h文件
```code
#import <UIKit/UIKit.h>
@interface ProgressView : UIView
//用于接收传值
@property (assign, nonatomic) CGFloat progress;
@end```
####ProgressView.m文件
```code
#import "ProgressView.h"
@interface ProgressView ()
//用于显示进度值
@property (strong, nonatomic) UILabel *label;
@end
@implementation ProgressView
- (UILabel *)label{
if (_label == nil) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 100, 20)];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor colorWithRed:0.069 green:0.362 blue:1.000 alpha:1.000];
self.label = label;
[self addSubview:label];
}
return _label;
}
- (void)drawRect:(CGRect)rect {
//获取上下文
CGContextRef cxt = UIGraphicsGetCurrentContext();
//路径
CGPoint center = CGPointMake(50, 50);
//半径
CGFloat radius = 50;
//开始弧度
CGFloat start = -M_PI_2;
//结束弧度
CGFloat end = start + self.progress * M_PI * 2;
# 注意: 该处创建路径的方法
//参数一: 值弧形的中心位置
//参数二: 弧形的半径
//参数三: 弧形的起始角度
//参数四: 弧形的结束角度
//参数五: 是否顺时针
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:start endAngle:end clockwise:YES];
//将路径添加到上下文
CGContextAddPath(cxt, path.CGPath);
//渲染
CGContextStrokePath(cxt);
}
//想要将显示到view上, 需要重写setting方法
- (void)setProgress:(CGFloat)progress{
_progress = progress;
self.label.text = [NSString stringWithFormat:@"%.1f%%", progress * 100];
//重写调用drawRect方法, 实时绘制进度
[self setNeedsDisplay];
}
@end