废话不多说,直接上代码
首先我们自定义一个UIView drawArcView.h
@interface drawView : UIView
- (instancetype)initWithFrame:(CGRect)frame;
@property (nonatomic, assign) CGFloat percentage;//暴露给外部,方便自定义进度条大小
@end
在drawArcView.m里面 我们重写
@interface drawView : UIView
- (instancetype)initWithFrame:(CGRect)frame;
@property (nonatomic, assign) CGFloat percentage;
@end
先定义几个宏
#define RADIUS self.frame.size.width/4 //圆半径
#define SRADIUS self.frame.size.width/4 -15 //小圆半径
#define ANGLE M_PI *_percentage
@interface drawView ()
@end
@implementation drawView
-(void)drawRect:(CGRect)rect{
CGContextRef context = UIGraphicsGetCurrentContext();//获得当前栈顶
CGContextSetRGBStrokeColor(context, 0, 0, 1, 1);
CGContextSetLineWidth(context, 1.0);
CGContextAddArc(context,self.center.x, self.center.y, RADIUS, 0, 2*M_PI, 0);
CGContextDrawPath(context, kCGPathStroke);//开始绘画边框圆
//内部边框圆
CGContextAddArc(context, self.center.x, self.center.y, SRADIUS, 0, 2*M_PI, 0);
CGContextDrawPath(context, kCGPathStroke);
//画外部扇形
UIColor *outColor = [UIColor blueColor];
[outColor set];
CGContextMoveToPoint(context, self.center.x, self.center.y);//必须移动圆心一次,不然填充起来就不是扇形,好奇心重的同学可以试试,和画圆的区别点
CGContextAddArc(context, self.center.x, self.center.y, RADIUS, M_PI/2 -ANGLE, M_PI/2 + ANGLE, 0);//注意开始角度和结束角度可以自定义,多嘴一句苹果的坐标系和正常笛卡尔坐标系的y轴方向刚好相反,同学们可以自己理解了
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFillStroke);
//画内实心填充圆,其实就是为了遮住外部扇形在内部的多余填充部分。
CGContextMoveToPoint(context, self.center.x, self.center.y);
UIColor *inColor = [UIColor whiteColor];
[inColor set];
CGContextClosePath(context);
CGContextAddArc(context, self.center.x, self.center.y, SRADIUS, 0, 2*M_PI, 0);
CGContextDrawPath(context, kCGPathFill);
//中间显示的百分比进度值
int percent = (int)(_percentage *100);
NSString *per = [NSString stringWithFormat:@"%d%",percent];
[per drawInRect:CGRectMake(self.center.x - 40, self.center.y -60, 100, 60) withAttributes:@{NSKernAttributeName:@13.0}];
}