项目中有加载网络图片的需求,加一个加载的进度条会提高用户体验,网络不好的时候会清晰的看到图片加载的进度,比让用户看着满屏幕空白好。下面是我们项目自己封装的圆形进度条,分享给大家。
其实实现原理很简单,只是根据图片加载的进度来绘制一个圆。
先来看.h文件,需要一个进度的属性和进度条展示位置的方法:
@property (nonatomic, assign) CGFloat progress; +(HMProgressView *)showHMProgressView:(UIView *)parentView :(CGFloat)viewHeight;
+(HMProgressView *)showHMProgressView:(UIView *)parentView :(CGFloat)viewHeight{ HMProgressView *progressView=(HMProgressView *)[parentView viewWithTag:999]; if (!progressView) { progressView=[[HMProgressView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)]; progressView.tag=999; progressView.center=parentView.center; progressView.y=viewHeight+kScreenWidth/2-25; progressView.backgroundColor=[UIColor clearColor]; [parentView addSubview:progressView]; } return progressView; } - (void)setProgress:(CGFloat)progress { _progress = progress; // 重新绘制 // 在view上做一个重绘的标记,当下次屏幕刷新的时候,就会调用drawRect. [self setNeedsDisplay]; if (_progress==1) {//加载完成时移除 [self removeFromSuperview]; } } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. // 当视图显示的时候会调用 默认只会调用一次 - (void)drawRect:(CGRect)rect { // Drawing code // 1.获取上下文 CGContextRef ctx = UIGraphicsGetCurrentContext(); // 2.拼接路径 CGPoint center = CGPointMake(25, 25); CGFloat radius = 25 - 2; 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]; CGContextSetLineCap(ctx, kCGLineCapRound); CGContextSetLineWidth(ctx, 4); // 3.把路径添加到上下文 [[UIColor lightGrayColor] set]; CGContextAddPath(ctx, path.CGPath); // 4.把上下文渲染到视图 CGContextStrokePath(ctx); }使用也很简单,项目中设置图片用的是第三方框架SDWebImage,在加载图片的方法中设置一下进度:
ImgProgressView *progressView=[ImgProgressView showImgProgressView:self.contentView :layoutFrame.photoRect.origin.y]; [self.orgPhoto setImageWithURL:[NSURL URLWithString:photoUrl] placeholderImage:nil options:SDWebImageProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize) { if (expectedSize!=-1) { [progressView setProgress:(CGFloat)receivedSize/expectedSize]; } } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { }];
原文地址:http://blog.csdn.net/july_sal/article/details/45819297