效果图
效果图
1 创建SKPPieChartView继承于UIView
2 SKPPieChartView.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface ChartModel : NSObject
@property(nonatomic,assign)float bili;//总值为1
@property(nonatomic,strong)UIColor *color;
@end
@interface SKPPieChartView : UIView
@property(nonatomic,assign)CGFloat startAngle;//开始弧度默认为0度
-(void)drawChartWithChartModelArray:(NSArray<ChartModel*>*)chartModelArray;
@end
NS_ASSUME_NONNULL_END
3 SKPPieChartView.m
#import "SKPPieChartView.h"
@implementation ChartModel
@end
@interface SKPPieChartView ()
@property(nonatomic,strong)NSArray<ChartModel*> *chartModelArray;
@end
@implementation SKPPieChartView
-(instancetype)initWithFrame:(CGRect)frame{
self=[super initWithFrame:frame];
if (self) {
self.layer.cornerRadius=frame.size.width/2;
self.layer.masksToBounds=YES;
}
return self;
}
-(void)drawChartWithChartModelArray:(NSArray<ChartModel*>*)chartModelArray{
self.chartModelArray=chartModelArray;
}
- (void)drawRect:(CGRect)rect {
CGFloat radius = rect.size.width/2;//半径
CGPoint center = CGPointMake(rect.size.width/2, rect.size.width/2);//圆心
CGFloat startAngle = self.startAngle;//开始弧度
CGFloat angle = 0;//所占弧度
CGFloat endAngle = 0;//结束弧度
for (int i = 0; i<self.chartModelArray.count; i++) {
ChartModel *model=self.chartModelArray[i];
angle=model.bili*M_PI*2;
endAngle=startAngle+angle;
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];
[path addLineToPoint:center];
[model.color set];
[path fill];
startAngle=endAngle;
}
}
@end
4 调用
#import "ViewController.h"
#import "SKPPieChartView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
ChartModel *model1=[[ChartModel alloc]init];
model1.color=[UIColor redColor];
model1.bili=0.4;
ChartModel *model2=[[ChartModel alloc]init];
model2.color=[UIColor yellowColor];
model2.bili=0.4;
ChartModel *model3=[[ChartModel alloc]init];
model3.color=[UIColor blueColor];
model3.bili=0.1;
SKPPieChartView *pieChartView=[[SKPPieChartView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
pieChartView.backgroundColor=[UIColor lightGrayColor];
pieChartView.startAngle=M_PI+M_PI_2;
[self.view addSubview:pieChartView];
[pieChartView drawChartWithChartModelArray:@[model1,model2,model3]];
}
@end
网友评论