AppDelegate默认
ViewController.h默认
ViewController.m
#import "ViewController.h"
#import "KMView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 加载一个 xib 怎么加载??
KMView * pieView = [KMView kmView];
//比例分配
pieView.array = @[@0.2,@0.2,@0.1,@0.1,@0.4];
pieView.frame = CGRectMake(0, 0, 300, 300);
[self.view addSubview:pieView];
}
KMView.xib
KMView.h
#import <UIKit/UIKit.h>
@interface KMView : UIView
@property (nonatomic ,strong) NSArray *array;
// 类方法:好处,不用创建对象.能用类方法,就不用,实例方法.
+ (instancetype)kmView;
@end
KMView.m
#define KSize self.bounds.size
#import "KMView.h"
@implementation KMView
// 类方法,快速创建
+ (instancetype)kmView {
return [[NSBundle mainBundle] loadNibNamed:@"KMView" owner:nil options:nil].firstObject;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// 画图. 算法. cos sin arctan
// 把这个参数暴露给用户.
// NSArray * arr = @[@0.3,@0.4,@0.2,@0.1];
// 108 90 108 36
CGFloat start = 0;
CGFloat end = 0;
for (int i = 0; i < self.array.count; i ++) {
// 计算当前的扇形的结束位置.
end = 2 * M_PI * [self.array[i] floatValue] + start; // 单纯的就是一个角度
// 画扇形
// MAX(<#A#>, <#B#>); 返回两个中的最大的一个
// MIN(<#A#>, <#B#>) 返回像个中的最小的一个
UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:[self arcCenter] radius:MIN(KSize.width, KSize.height) * 0.5 - 10 startAngle:start endAngle:end clockwise:30];
// 往圆心连线
[path addLineToPoint:[self arcCenter]];
// 设置颜色
[[self randomColor] set];
// 渲染
[path fill];
// 在当前绘制结束的时候,把结束的位置,下一个的开始.
start = end;
}
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 重绘
[self setNeedsDisplay];
}
// 返回中心点的 方法
- (CGPoint)arcCenter
{
return CGPointMake(KSize.width * 0.5, KSize.height * 0.5);
}
// 随机颜色
- (UIColor *)randomColor
{
CGFloat r = arc4random() % 256 / 255.0;
CGFloat g = arc4random() % 256 / 255.0;
CGFloat b = arc4random() % 256 / 255.0;
return [UIColor colorWithRed:r green:g blue:b alpha:1];
}
@end