1.效果圖如下:
屏幕快照 2016-08-26 上午10.12.54.png
2.畫餅圖實現(xiàn)步驟如下:
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(@"隨機數(shù) -- %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];
}
第一次寫博客,有很多不足之處,歡迎大家指正公罕,謝謝!