您的位置:首页 > 移动开发 > IOS开发

iOS绘制 - 自定义制作进度条

2016-04-07 14:51 357 查看
I. ProgressView的类

ProgressView.h

#import <UIKit/UIKit.h>

@interface ProgressView : UIView

@property (nonatomic, assign) CGFloat progress;

@end


ProgressView.m

#import "ProgressView.h"

@interface ProgressView ()
@property (nonatomic, strong) UILabel *progressLabel; //进度条Label
@end

@implementation ProgressView

- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
//初始化
}
return self;
}

//getter方法里面初始化, 并且设置progressLabel
- (UILabel *)progressLabel
{
if (_progressLabel == nil) {

CGFloat w = self.bounds.size.width;
CGFloat h = self.bounds.size.height;

UILabel *label = [[UILabel alloc] init];
label.center = CGPointMake(w * 0.5, h * 0.5);
label.bounds = CGRectMake(0, 0, w, 30);
label.textAlignment = NSTextAlignmentCenter;
[self addSubview:label];

_progressLabel = label;
}

return _progressLabel;
}

//progress的setter方法
- (void)setProgress:(CGFloat)progress
{
_progress = progress;

self.progressLabel.text = [NSString stringWithFormat:@"%.2f%%", progress * 100];

//重绘, 会调用drawRect:rect的方法
[self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {

CGContextRef ctx = UIGraphicsGetCurrentContext();

CGFloat w = self.bounds.size.width;
CGFloat h = self.bounds.size.height;

//圆点
CGPoint center = CGPointMake(w * 0.5, h * 0.5);
//半径
CGFloat radius = w * 0.5 - 5;
//起点角度: 以x轴正方向所在位置为0
CGFloat startA = -M_PI_2;
//终点角度
CGFloat endA = -M_PI_2 + _progress * 2 * M_PI;

//arc:弧
//clockwise : 顺时针
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];

//设置笔触的颜色
[[UIColor blueColor] set];

//设置笔触宽度为5px
CGContextSetLineWidth(ctx, 5);

CGContextAddPath(ctx, path.CGPath);
CGContextStrokePath(ctx);
}

@end


II. 控制器调用演示

#import "ViewController.h"
#import "ProgressView.h"    //引用进度条

@interface ViewController ()
@property (weak, nonatomic) IBOutlet ProgressView *progressView;
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
}

//调用ProgressView的progress属性, 来设置其值
- (IBAction)valueChanged:(UISlider *)sender {
self.progressView.progress = sender.value;
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  进度条 自定义