繪製下載進度(Quartz2D)

weixin_33866037發表於2015-11-12
831339-5c66032494565aba.png
Snip20151029_3.png

1.思路分析

  • 進度肯定是不停改變的,所以我們肯定需要定時器NSTimer操作,監聽Label控制元件進度文字的改變,從而來設計下載檢視的圓形

  • 設計下載進度檢視,需要我們提供進度值 -> 來確定繪製圓的大小

2.實現

  • 自定義DrawView檢視,用來繪製下載進度
// .h檔案
 #import <UIKit/UIKit.h>
@interface DrawView : UIView

@property (nonatomic, assign) CGFloat value;

@end

// . m檔案

#import "DrawView.h"
@implementation DrawView
- (void)drawRect:(CGRect)rect {
    // Drawing code
    
    UIBezierPath *path = [[UIBezierPath alloc] init];
    CGPoint center = CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.5);
    CGFloat radius = self.frame.size.width * 0.5 - 5;
    CGFloat startAngle = 0;
    CGFloat endAngle = self.value / 100 * M_PI * 2;
    [path addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];
    
    [path stroke];
}
@end
  • 使用DrawView,實現下載進度動態顯示
#import "ViewController.h"
#import "DrawView.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UILabel *lableView;
@property (weak, nonatomic) IBOutlet DrawView *grayView;

@property (nonatomic, weak) NSTimer *timer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
   self.lableView.text = @"0.0%";
  [self.lableView sizeToFit];
}


// 改變lable的文字,然後重繪灰色檢視上的進度條進度
- (void)change{
   NSString *value = [self.lableView.text stringByReplacingOccurrencesOfString:@"%" withString:@""];
    
    if ([value doubleValue] >= 100) {
         [NSTimer initialize];
        return;
    }
    
    CGFloat lastValue = [value doubleValue] + 1;

    self.lableView.text = [NSString stringWithFormat:@"%.0f%%", lastValue];
    [self.lableView sizeToFit];
    
    // 重繪
    self.grayView.value = lastValue;
    // setNeedsDisplay方法會呼叫drawRect:方法,重繪灰色檢視上的進度條進度
    [self.grayView setNeedsDisplay];
}

- (void)touchesBegan:(nonnull NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{ 
    // 建立定時器
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(change) userInfo:nil repeats:YES];
}

- (void)dealloc{
    // 停止定時器
   [NSTimer initialize];  
}
@end

相關文章