(素材源码)猫猫学IOS(二十九)UI之Quartz2D自定义下载控件

猫猫分享,必须精品

素材代码地址:http://download.csdn.net/detail/u013357243/8640353
原创文章,欢迎转载。转载请注明:翟乃玉的博客
地址:http://blog.csdn.net/u013357243?viewmode=contents

效果

这里写图片描述

代码

NYProgressView.m

//
//  NYProgressView.m
//  下载进度条
//
//  Created by apple on 15-4-27.
//  Copyright (c) 2015年 znycat. All rights reserved.
//

#import "NYProgressView.h"
@interface NYProgressView()


@property (nonatomic,weak) UILabel *label;
@end


@implementation NYProgressView


/**label的懒加载*/
-(UILabel *)label
{
    if (_label == nil) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
        label.textAlignment = NSTextAlignmentCenter;
        [self addSubview:label];
        _label = label;
    }
    return _label;
}


-(void)setProgress:(CGFloat)progress
{
    _progress = progress;
    self.label.text = [NSString stringWithFormat:@"%.2f%%", progress*100];

    //重新绘制 在view上做一个重绘标记,当下次屏幕刷新的时候,调用drawRect。
    [self setNeedsDisplay];
}


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

/**画画 当视图显示的时候,默认只调用一次
 解决办法://重新绘制 在view上做一个重绘标记,当下次屏幕刷新的时候,调用drawRect。
 [self setNeedsDisplay];

 */
- (void)drawRect:(CGRect)rect
{
    // 1:获取上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // 2:拼接路径
    /*我们需要画一个圆图*/

    CGPoint center = CGPointMake(50, 50);//圆心
    CGFloat radius = 43;//半径
    CGFloat startA = -M_PI_2 ;//起始角度
    CGFloat endA = -M_PI_2 + _progress * M_PI * 2 ;//结束角度。

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

    //3:把路径添加到上下文。
    CGContextAddPath(ctx, path.CGPath);
    //设置颜色为红色
    [[UIColor redColor] set];
    //设置线条的宽度
    CGContextSetLineWidth(ctx, 10);
    //设置两端的样式为圆角
    CGContextSetLineCap(ctx,kCGLineCapRound);


    //4:把上下文渲染到视图。
    CGContextStrokePath(ctx);
}


@end

NYViewController.m

//
//  NYViewController.m
//  下载进度条
//
//  Created by apple on 15-4-27.
//  Copyright (c) 2015年 znycat. All rights reserved.
//

#import "NYViewController.h"
#import "NYProgressView.h"

@interface NYViewController ()
@property (weak, nonatomic) IBOutlet NYProgressView *progressView;

@end

@implementation NYViewController

/**滑动slider发生的事件*/
- (IBAction)valueChange:(UISlider *)sender {
    NSLog(@"%f",sender.value);
    _progressView.progress = sender.value;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
原文地址:https://www.cnblogs.com/znycat/p/4521022.html