http://www.2cto.com/kf/201505/400351.html
项目中有加载网络图片的需求,加一个加载的进度条会提高用户体验,网络不好的时候会清晰的看到图片加载的进度,比让用户看着满屏幕空白好。下面是我们项目自己封装的圆形进度条,分享给大家。
其实实现原理很简单,只是根据图片加载的进度来绘制一个圆。
先来看.h文件,需要一个进度的属性和进度条展示位置的方法:
1
2
3
|
@property
(nonatomic, assign) CGFloat progress;
+(HMProgressView *)showHMProgressView:(UIView *)parentView :(CGFloat)viewHeight;
|
再看.m文件中的实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
+(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);
}
|
1
2
3
4
5
6
7
8
9
10
11
|
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)
{
}];
|