标签:style blog http io ar color sp strong on
用CALayer实现下载进度条
效果:
源码:
// // ViewController.m // ProgressView // // Created by YouXianMing on 14/11/18. // Copyright (c) 2014年 YouXianMing. All rights reserved. // #import "ViewController.h" @interface ViewController () @property (nonatomic, strong) NSTimer *timer; @property (nonatomic, strong) CALayer *layer; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor blackColor]; // CALayer _layer = [CALayer layer]; _layer.frame = CGRectMake(50, 50, 200, 2); _layer.backgroundColor = [UIColor redColor].CGColor; [self.view.layer addSublayer:_layer]; // 定时器 _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(timerEvent) userInfo:nil repeats:YES]; } /** * 定时器 */ - (void)timerEvent { // 显式动画 _layer.frame = CGRectMake(50, 50, arc4random()%200, 2); } @end
封装后的源码:
// // ProgressView.h // ProgressView // // Created by YouXianMing on 14/11/18. // Copyright (c) 2014年 YouXianMing. All rights reserved. // #import <UIKit/UIKit.h> @interface ProgressView : UIView @property (nonatomic, strong) UIColor *progressColor; @property (nonatomic, assign) CGFloat progress; @end
// // ProgressView.m // ProgressView // // Created by YouXianMing on 14/11/18. // Copyright (c) 2014年 YouXianMing. All rights reserved. // #import "ProgressView.h" @interface ProgressView () { CALayer *_backLayer; CGFloat _frameWidth; CGFloat _layerWidth; } @end @implementation ProgressView - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { _backLayer = [CALayer layer]; _frameWidth = self.bounds.size.width; _layerWidth = 0; _backLayer.frame = CGRectMake(0, 0, _layerWidth, frame.size.height); [self.layer addSublayer:_backLayer]; } return self; } @synthesize progressColor = _progressColor; - (void)setProgressColor:(UIColor *)progressColor { _progressColor = progressColor; _backLayer.backgroundColor = _progressColor.CGColor; } - (UIColor *)progressColor { return _progressColor; } @synthesize progress = _progress; - (void)setProgress:(CGFloat)progress { _progress = progress; CGRect rect = _backLayer.frame; if (_progress <= 0) { rect.size.width = 0; } else if (_progress >= 1) { rect.size.width = _frameWidth; } else { rect.size.width = _progress * _frameWidth; } _backLayer.frame = rect; } - (CGFloat)progress { return _progress; } @end
标签:style blog http io ar color sp strong on
原文地址:http://www.cnblogs.com/YouXianMing/p/4107001.html