iOS 饼状图

2016-08-26  本文已影响302人  噜噜土豆

1.效果图如下:

屏幕快照 2016-08-26 上午10.12.54.png

2.画饼图实现步骤如下:

1.新建PieView分类

import <UIKit/UIKit.h>

@interface PieView : UIView

@end

import "PieView.h"

@implementation PieView

-(instancetype)initWithFrame:(CGRect)frame{

if (self = [super initWithFrame:frame]) {
    
}
return self;

}

-(void)drawRect:(CGRect)rect{

NSArray * data = @[@10,@30,@40,@20];

    //1.获取图形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();

    //2.拼接路径
CGPoint center = CGPointMake(125, 125);

CGFloat radius = 120;

CGFloat startA = 0;

CGFloat angle = 0;

CGFloat endA = 0;

for (NSNumber * number in data) {

    //2.拼接路径

    startA = endA;
    
    angle = number.intValue/100.0 * M_PI * 2;
    
    endA = startA + angle;
    
    UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
    
    [path addLineToPoint:center];
    
    [[UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1] set];
    
   //把路径添加到上下文

    CGContextAddPath(ctx, path.CGPath);
    
    //把路径添加到上下文
    CGContextFillPath(ctx);
    
}

}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

CGFloat a = arc4random_uniform(6);

NSLog(@"随机数 -- %f",a);

[self setNeedsDisplay];

}

@end

3.在ViewController上添加PieView:

#import "ViewController.h"

#import "PieView.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

PieView * pieView = [[PieView alloc]initWithFrame:CGRectMake(50, 50, 300, 300)];

pieView.backgroundColor = [UIColor whiteColor];

[self.view addSubview:pieView];

}

第一次写博客,有很多不足之处,欢迎大家指正,谢谢!

上一篇 下一篇

猜你喜欢

热点阅读