載入網路圖片時,畫面一片空白是最讓人焦慮的體驗。加一個進度指示,使用者立刻知道「正在發生什麼、還要等多久」。本文分享專案裡自製的圓形進度條,核心原理其實只是依進度畫一段弧線。
只需要一個進度屬性與一個便利的顯示方法:
@property (nonatomic, assign) CGFloat progress;
+ (HMProgressView *)showHMProgressView:(UIView *)parentView :(CGFloat)viewHeight;
顯示方法用 tag 做重複呼叫時的保護,避免同一畫面疊出好幾個進度條:
+ (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;
[self setNeedsDisplay]; // 標記重繪,下次刷新時才會呼叫 drawRect:
if (_progress == 1) {
[self removeFromSuperview]; // 載入完成即移除
}
}
畫弧線只要三個資訊:圓心、半徑、起訖角度。起始角固定從正上方(-M_PI_2)開始,結束角依進度往順時針方向推進。
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
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);
[[UIColor lightGrayColor] set];
CGContextAddPath(ctx, path.CGPath);
CGContextStrokePath(ctx);
}
專案用 SDWebImage 載圖,它的 progress block 剛好能直接餵給我們的進度條:
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) {
}];
這裡有兩個實務細節值得注意。第一,expectedSize 為 -1 代表伺服器未回傳 Content-Length,此時無法算百分比,必須先擋掉避免算出負值。第二,SDWebImage 搭配 SDWebImageProgressiveDownload 還會附帶「漸進式顯示模糊預覽」的效果,與圓形進度條互補,網路慢時體驗會好很多。
另外提醒:setNeedsDisplay 只是「登記」重繪請求,真正作畫發生在 drawRect:。若進度更新頻繁,系統會自動合併同一輪 runloop 內的多次請求,所以不必擔心效能;但也別在 drawRect: 裡做運算密集的工作,那會直接拖慢滾動幀率。