简单快速实现UIProgressView进度条圆角

关键方法:

  1. 利用贝塞尔生成圆角图片
  2. 圆角不变形拉伸拉伸图片resizableImageWithCapInsets

PS:UIProgressView在iOS7,iOS8.3上会出现设置trackimage和ProgressImage无效Bug,具体解决查阅:HJProgressView

代码如下

1
2
3
4
5
6
7
8
9
10
11
#import <UIKit/UIKit.h>

@interface UIProgressView (Radius)

- (void)setRadiusTrackColor:(UIColor *)trackColor ;
- (void)setRadiusProgressColor:(UIColor *)progressColor;
- (void)setRadiusTrackColor:(UIColor *)trackColor
progressColor:(UIColor *)progressColor;

@end

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
#import "UIProgressView+Radius.h"

@implementation UIProgressView (Radius)

- (void)setRadiusTrackColor:(UIColor *)trackColor
{
UIImage *trackImage = [self imageWithColor:trackColor cornerRadius:self.frame.size.height/2.0];
[self setTrackImage:trackImage];
}

- (void)setRadiusProgressColor:(UIColor *)progressColor
{
UIImage *progressImage = [self imageWithColor:progressColor cornerRadius:self.frame.size.height/2.0];
[self setProgressImage:progressImage];

}

- (void)setRadiusTrackColor:(UIColor *)trackColor
progressColor:(UIColor *)progressColor
{

[self setRadiusTrackColor:trackColor];
[self setRadiusProgressColor:progressColor];
}

//最小尺寸---1px
static CGFloat edgeSizeWithRadius(CGFloat cornerRadius) {
return cornerRadius * 2 + 1;
}

- (UIImage *)imageWithColor:(UIColor *)color
cornerRadius:(CGFloat)cornerRadius {
CGFloat minEdgeSize = edgeSizeWithRadius(cornerRadius);
CGRect rect = CGRectMake(0, 0, minEdgeSize, minEdgeSize);
UIBezierPath *roundedRect = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius];
roundedRect.lineWidth = 0;
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0f);
[color setFill];
[roundedRect fill];
[roundedRect stroke];
[roundedRect addClip];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return [image resizableImageWithCapInsets:UIEdgeInsetsMake(cornerRadius, cornerRadius, cornerRadius, cornerRadius)];
}

@end

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (void)viewDidLoad {
[super viewDidLoad];
UIProgressView *progressView=[[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
progressView.frame=CGRectMake([UIScreen mainScreen].bounds.size.width/2-150, 50, 300, 50);
[self.view addSubview:progressView];

[progressView setProgress:0.68 animated:YES];

//修改progressView高度
progressView.transform=CGAffineTransformMakeScale(1.0, 8.0);

//设置进度条颜色和圆角
[progressView setRadiusTrackColor:RGBCOLOR(231, 233, 238) progressColor:RGBCOLOR(255, 153,0)];
}

文章作者: kyren
文章链接: http://huluo666.github.io/2016/03/24/简单快速实现UIProgressView进度条圆角/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Kyren's Blog