項目中有加載網絡圖片的需求,加一個加載的進度條會提升用戶體驗,網絡很差的時候會清晰的看到圖片加載的進度,比讓用戶看着滿屏幕空白好。下面是咱們項目本身封裝的圓形進度條,分享給你們。java
其實實現原理很簡單,只是根據圖片加載的進度來繪製一個圓。網絡
先來看.h文件,須要一個進度的屬性和進度條展現位置的方法:框架
@property (nonatomic, assign) CGFloat progress; +(HMProgressView *)showHMProgressView:(UIView *)parentView :(CGFloat)viewHeight;
再看.m文件中的實現:ide
+(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,在加載圖片的方法中設置一下進度:atom
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) { }];