代码改变生活

饼图

 

 1 //
 2 //  ViewController.m
 3 //  画饼状图
 4 //
 5 //  Created by zjj on 15/7/1.
 6 //  Copyright (c) 2015年 zjj. All rights reserved.
 7 //
 8 
 9 #import "ViewController.h"
10 #import "DJPieView.h"
11 @interface ViewController ()
12 
13 @end
14 
15 @implementation ViewController
16 
17 - (void)viewDidLoad {
18     [super viewDidLoad];
19     DJPieView *pieView = [[DJPieView alloc]initWithFrame:CGRectMake(10, 50, 200, 200)];
20     pieView.backgroundColor = [UIColor grayColor];
21     [self.view addSubview:pieView];
22     pieView.sessions = @[@10,@20,@5,@13,@15,@7,@30];
23     pieView.sessionsColor = @[[UIColor redColor],[UIColor blueColor],[UIColor whiteColor],[UIColor blackColor],[UIColor yellowColor],[UIColor orangeColor],[UIColor greenColor]];
24 }
25 
26 @end

 

//
//  DJPieView.h
//  画饼状图
//
//  Created by zjj on 15/7/1.
//  Copyright (c) 2015年 zjj. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface DJPieView : UIView
@property (nonatomic,strong)NSArray *sessions;
@property (nonatomic,strong)NSArray *sessionsColor;
@end

 

//
//  DJPieView.m
//  画饼状图
//
//  Created by zjj on 15/7/1.
//  Copyright (c) 2015年 zjj. All rights reserved.
//

#import "DJPieView.h"

@implementation DJPieView

- (void)drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    NSInteger count = self.sessions.count;
    if (count == 0) return;
    CGFloat cententX = rect.size.width*0.5;
    CGFloat cententY = rect.size.height*0.5;
    CGFloat reaius = cententX;
    CGFloat startAngle = 0;
    
    NSInteger sum = 0;
    for (NSInteger i = 0 ; i < count; i++) {
        sum += [self.sessions[i] integerValue];
    }
    
    for (NSInteger i = 0 ; i < count; i++) {
        // 设定颜色
        [(UIColor *)self.sessionsColor[i] set];
        // 计算数据占据整个圆的比例
        CGFloat scale = [self.sessions[i] integerValue] / (sum * 1.0);
        //计算结束位置 比例*两个半圆
        CGFloat endAngle = startAngle + scale * 2 * M_PI;
        //指定弧的中心点
        CGContextMoveToPoint(ctx, cententX, cententY);
        CGContextAddArc(ctx, cententX, cententY, reaius, startAngle, endAngle, 0);
        CGContextFillPath(ctx);
        //重新设置起点位置 供下次循环使用
        startAngle = endAngle;
    }
}
@end

 

posted on 2015-07-01 02:53  张大少。  阅读(275)  评论(0编辑  收藏  举报

导航

繁星纵变 智慧永恒