天天看點

iOS繪制餅狀圖效果圖1 建立SKPPieChartView繼承于UIView2 SKPPieChartView.h3 SKPPieChartView.m4 調用

效果圖

iOS繪制餅狀圖效果圖1 建立SKPPieChartView繼承于UIView2 SKPPieChartView.h3 SKPPieChartView.m4 調用

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