iOS绘制饼状图

效果图

效果图

1 创建SKPPieChartView继承于UIView

2 SKPPieChartView.h

#import 

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*)chartModelArray;


@end

NS_ASSUME_NONNULL_END

3 SKPPieChartView.m

#import "SKPPieChartView.h"

@implementation ChartModel

@end


@interface SKPPieChartView ()

@property(nonatomic,strong)NSArray *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*)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

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

你可能感兴趣的:(iOS绘制饼状图)