標籤:
:
步驟:
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
iOS Quartz2D類比下載進度條