項目中有加載網絡圖片的需求,加一個加載的進度條會提高用戶體驗,網絡不好的時候會清晰的看到圖片加載的進度,比讓用戶看著滿屏幕空白好。下面是我們項目自己封裝的圓形進度條,分享給大家。
其實實現原理很簡單,只是根據圖片加載的進度來繪制一個圓。
先來看.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) { }];