在运行一下,我们看下效果

可使有没有觉得上面的代码很多重复的?对的,我们可以封装一个方法 那么重构后的代码我就一次性的贴上去了
#import "pieview.h"
//直径
#define radius 50
#define PI 3.14159265358979323846
@implementation pieview
//计算度转弧度
static inline float radians(double degrees) {
return degrees * PI / 180;
}
static inline void drawArc(CGContextRef ctx, CGPoint point, float angle_start, float angle_end, UIColor* color) {
CGContextMoveToPoint(ctx, point.x, point.y);
CGContextSetFillColor(ctx, CGColorGetComponents( [color CGColor]));
CGContextAddArc(ctx, point.x, point.y, radius, angle_start, angle_end, 0);
//CGContextClosePath(ctx);
CGContextFillPath(ctx);
}
-(void)drawRect:(CGRect)rect
{
CGPoint cent=CGPointMake((self.frame.size.width/2)-radius/2, (self.frame.size.height/2)-radius/2);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextClearRect(ctx, rect);
float angle_start = radians(0.0);
float angle_end = radians(121.0);
drawArc(ctx, cent, angle_start, angle_end, [UIColor yellowColor]);
angle_start = angle_end;
angle_end = radians(228.0);
drawArc(ctx, cent, angle_start, angle_end, [UIColor greenColor]);
angle_start = angle_end;
angle_end = radians(260);
drawArc(ctx, cent, angle_start, angle_end, [UIColor orangeColor]);
angle_start = angle_end;
angle_end = radians(360);
drawArc(ctx, cent, angle_start, angle_end, [UIColor purpleColor]);
}
@end
看下运行效果图

如果我们中途数据变了 想要改一下图形怎么办呢?
那么我们就需要用到这个
//通知自定义的view重新绘制图形
// [self setNeedsDisplay];
这时候我们就要pieview向外界提供一个接口属性,这是我做的模拟5面之后改变圆形的直径大小
.h文件
#import <UIKit/UIKit.h>
@interface pieview : UIView
//直径
@property(nonatomic,assign)float radius;
@end
.m文件
#import "pieview.h"
#define PI 3.14159265358979323846
@implementation pieview
//计算度转弧度
static inline float radians(double degrees) {
return degrees * PI / 180;
}
static inline void drawArc(CGContextRef ctx, CGPoint point, float angle_start, float angle_end, UIColor* color,float radius) {
CGContextMoveToPoint(ctx, point.x, point.y);
CGContextSetFillColor(ctx, CGColorGetComponents( [color CGColor]));
CGContextAddArc(ctx, point.x, point.y, radius, angle_start, angle_end, 0);
//CGContextClosePath(ctx);
CGContextFillPath(ctx);
}
-(void)drawRect:(CGRect)rect
{
CGPoint cent=CGPointMake((self.frame.size.width/2)-self.radius/2, (self.frame.size.height/2)-self.radius/2);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextClearRect(ctx, rect);
float angle_start = radians(0.0);
float angle_end = radians(121.0);
drawArc(ctx, cent, angle_start, angle_end, [UIColor yellowColor],self.radius);
angle_start = angle_end;
angle_end = radians(228.0);
drawArc(ctx, cent, angle_start, angle_end, [UIColor greenColor],self.radius);
angle_start = angle_end;
angle_end = radians(260);
drawArc(ctx, cent, angle_start, angle_end, [UIColor orangeColor],self.radius);
angle_start = angle_end;
angle_end = radians(360);
drawArc(ctx, cent, angle_start, angle_end, [UIColor purpleColor],self.radius);
}
-(void)setRadius:(float)radius
{
_radius=radius;
[self setNeedsDisplay];
}
@end










