iOS Quartz2D模拟下载进度条
效果图:
步骤:
1.在StoryBoard中拖入一个控制器添加UISlider和UIView 2个控件
2.在控制器中连线监听UISlider的值变化事件、HJProgressView属性,把变化的值传递给自定义UIView
3.自定义HJProgressView重写progressValue属性set方法,重绘视图中得文字和弧度值
控制器代码:
#import "ViewController.h" #import "HJProgressView.h" @interface ViewController () @property (nonatomic,strong) IBOutlet HJProgressView *progressView; - (IBAction)didSliderValueChange:(UISlider *)sender; @end @implementation ViewController - (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. } /** * sender.value值 0.0~1.0 * * @param sender <#sender description#> */ - (IBAction)didSliderValueChange:(UISlider *)sender { NSLog(@"%f",sender.value); self.progressView.progressValue = sender.value; } @end
自定义视图代码:
// // HJProgressView.m // 画进度条 // // Created by HJiang on 15/1/2. // Copyright (c) 2015年 HJiang. All rights reserved. // #import "HJProgressView.h" @interface HJProgressView() // 定义属性保存上次的弧度起始 //@property (nonatomic,assign) CGFloat endAngle; @end @implementation HJProgressView - (void)setProgressValue:(float)progressValue{ _progressValue = progressValue; // 重新绘制ProgressView图形 [self setNeedsDisplay]; } /** * 绘制进度条 * x,y 圆心 * radius 半径 * startAngle 画弧的起始位置 * endAngel 画弧的结束位置 * clockwise 0 顺针 1 逆时针 * @param rect rect description */ - (void)drawRect:(CGRect)rect{ // 1.设置进度文字 CGFloat w = 40; CGFloat h = 30; CGFloat x = 13; CGFloat y = rect.size.height/2-5; // NSString *progressText = [NSString stringWithFormat:@"%.02f",self.progressValue]; // 输出进度百分比数字 NSMutableString *progressText = [NSMutableString string]; [progressText appendFormat:@"%.01f",self.progressValue * 100]; [progressText appendString:@"%"]; // 控制文字字体大小和颜色属性 NSDictionary *attrs = @{NSFontAttributeName:[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:[UIColor redColor]}; [progressText drawInRect:CGRectMake(x, y, w, h) withAttributes:attrs]; CGContextRef ctx = UIGraphicsGetCurrentContext(); // 设置颜色 CGContextSetRGBStrokeColor(ctx, 0.5, 0.5, 0.5, 1); // 设置线条大小 CGContextSetLineWidth(ctx, 3); // 2.绘制弧形进度 CGFloat endAngle = self.progressValue * 2 * M_PI - M_PI_4; CGContextAddArc(ctx, 30, 30, 25,-M_PI_4, endAngle, 0); CGContextStrokePath(ctx); } @end
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。