1.饼状图
效果如下
方法 (void)pie
2.环形图
方法 方法 (void)circle
//
// pieView.m
// 04-饼图
//
// Created by 李亮 on 2016/12/1.
// Copyright © 2016年 www.thelast.com. All rights reserved.
//
#import "pieView.h"
@interface pieView()
@property (nonatomic, strong) NSArray * dataArray;
@end
@implementation pieView
- (NSArray *)dataArray{
if (_dataArray == nil) {
_dataArray = @[@25,@25,@50];
}
return _dataArray;
}
- (void)drawRect:(CGRect)rect {
// [self pie];
[self circle];
}
- (void)pie{
CGPoint startPoint = CGPointMake(self.bounds.size.width * 0.5, self.bounds.size.height * 0.5);
CGFloat radius = self.bounds.size.width * 0.5 - 30;
CGFloat startAngle = 0;
CGFloat endAngle = 0;
for (int index = 0; index < self.dataArray.count; index++) {
startAngle = endAngle;
NSNumber * num = self.dataArray[index];
CGFloat angle = num.integerValue / 100.0 * M_PI * 2;
endAngle = startAngle + angle;
UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:startPoint radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];
[[self randomColor] set];
[path addLineToPoint:startPoint];
[path fill];
}
}
- (void)circle{
CGPoint startPoint = CGPointMake(self.bounds.size.width * 0.5, self.bounds.size.height * 0.5);
CGFloat radius = self.bounds.size.width * 0.5 - 30;
CGFloat startAngle = 0;
CGFloat endAngle = 0;
for (int index = 0; index < self.dataArray.count; index++) {
CAShapeLayer * shapeLayer = [CAShapeLayer layer];
startAngle = endAngle;
NSNumber * num = self.dataArray[index];
CGFloat angle = num.integerValue / 100.0 * M_PI * 2;
endAngle = startAngle + angle;
UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:startPoint radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];
// [path addLineToPoint:startPoint];
shapeLayer.path = path.CGPath;
shapeLayer.lineWidth = 30;
shapeLayer.fillColor = [UIColor clearColor].CGColor;
shapeLayer.strokeColor = [self randomColor].CGColor;
[self.layer addSublayer:shapeLayer];
// [path fill];
}
}
- (UIColor *)randomColor{
CGFloat r = arc4random_uniform(255) / 255.0;
CGFloat g = arc4random_uniform(255) / 255.0;
CGFloat b = arc4random_uniform(255) / 255.0;
return [UIColor colorWithRed:r green:g blue:b alpha:1.0];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self setNeedsDisplay];
}
//- (void)test{
// CGPoint startPoint = CGPointMake(rect.size.width * 0.5, rect.size.height * 0.5);
// CGFloat radius = rect.size.width * 0.5 - 30;
// CGFloat startAngle = 0;
// NSNumber * num = self.dataArray[0];
// CGFloat endAngle = num.integerValue * M_PI * 2;
// UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:startPoint radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];
//
// [[self randomColor] set];
// [path stroke];
//}
@end