iOS 绘制下载进度条progressView

效果图:

iOS 绘制下载进度条progressView_第1张图片

界面实现:
(1)在storyBoard控制器的View上拖一个View控件绑定ProgressView类;
(2)再拖一个UILabel到ProgressView上设置相同的frame;
(3)在下面拖一个UISlider;
(4) 给slider,label,progressView 脱一个成员属性到控制器;
(5)监听slider的valueChange方法;
核心代码:

//
//  ViewController.m
//  下载进度条
//
//  Created by llkj on 2017/8/21.
//  Copyright © 2017年 LayneCheung. All rights reserved.
//

#import "ViewController.h"
#import "ProgressView.h"

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

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (IBAction)valueChange:(UISlider *)sender {

    self.valueTitle.text = [NSString stringWithFormat:@"%.2f%%", sender.value * 100];

    self.progressView.progressValue = sender.value;
}




@end

ProgressView.h

//
//  ProgressView.h
//  下载进度条
//
//  Created by llkj on 2017/8/21.
//  Copyright © 2017年 LayneCheung. All rights reserved.
//

#import 

@interface ProgressView : UIView

@property (nonatomic, assign) CGFloat progressValue;
@end

ProgressView.m

//
//  ProgressView.m
//  下载进度条
//
//  Created by llkj on 2017/8/21.
//  Copyright © 2017年 LayneCheung. All rights reserved.
//

#import "ProgressView.h"

@implementation ProgressView

- (void)setProgressValue:(CGFloat)progressValue{

    _progressValue = progressValue;

    //手动调用drawRect方法不会创建跟View相关联的上下文
    //只有通过系统调用该方法才会创建跟View相关联的上下文
//    [self drawRect:self.bounds];

    //重绘(系统自动帮你调用drawRect:)
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    // Drawing code

    CGContextRef ref = UIGraphicsGetCurrentContext();

    CGPoint center = CGPointMake(rect.size.width * 0.5, rect.size.height * 0.5);

    CGFloat radius = rect.size.width * 0.5 - 10;

    CGFloat startA = -M_PI_2;

    CGFloat angle = self.progressValue * M_PI * 2;

    CGFloat endA = startA + angle;

    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];

    CGContextAddPath(ref, path.CGPath);

    CGContextStrokePath(ref);
}


@end

你可能感兴趣的:(iOS)