iOS 圖片載入 圓形進度條
項目中有載入網狀圖片的需求,加一個載入的進度條會提高使用者體驗,網路不好的時候會清晰的看到圖片載入的進度,比讓使用者看著滿螢幕空白好。下面是我們項目自己封裝的圓形進度條,分享給大家。
其實實現原理很簡單,只是根據圖片載入的進度來繪製一個圓。
先來看.h檔案,需要一個進度的屬性和進度條展示位置的方法:
@property (nonatomic, assign) CGFloat progress;+(HMProgressView *)showHMProgressView:(UIView *)parentView :(CGFloat)viewHeight;
再看.m檔案中的實現:
+(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) { }];