1、用贝塞尔曲线画圆饼图,然后根具 UIBezierPath 中的 containsPoint 方法,判断点击是在哪个扇形区域内
元素类:
@interface WYPicChartsObj : NSObject
@property(strong)UIColor *fillColor;
@property(assign)float percent;
-(id)initWithFillcolor:(UIColor *)color percent:(float)percent;
@end
@implementation WYPicChartsObj
@synthesize fillColor = _fillColor;
@synthesize percent = _percent;
-(id)initWithFillcolor:(UIColor *)color percent:(float)percent{
self = [super init];
self.fillColor = color;
self.percent = percent;
return self;
}
@end
展示类
#import <UIKit/UIKit.h>
@protocol WYPieChartsDelegate <NSObject>
-(void)pieChartsDidSelectIndex:(NSInteger)index;
@end
@interface WYPieCharts : UIView
{
NSMutableArray *_mutablePath;
}
@property(strong,readonly)NSMutableArray *mutablePath;
@property(strong,readwrite)NSMutableArray *dataArray;
@property(assign,nonatomic)id<WYPieChartsDelegate>delegate;
@end
#import "WYPieCharts.h"
@implementation WYPieCharts
@synthesize delegate;
@synthesize mutablePath = _mutablePath;
@synthesize dataArray = _dataArray;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
_mutablePath = [NSMutableArrayarrayWithCapacity:12];
}
return self;
}
#define radius_s 100
-(UIBezierPath *)addPath:(CGPoint)center start:(float) angle_start end:(float) angle_end color:(UIColor *)color
{
UIBezierPath *p = [UIBezierPathbezierPathWithArcCenter:center radius:radius_sstartAngle:angle_start endAngle:angle_endclockwise:YES];
[p addLineToPoint:center];
[p closePath];
[color setFill];
[p fill];
return p;
}
- (void)drawRect:(CGRect)rect {
if([_dataArray count] <= 0) return;
CGContextRef ctx =UIGraphicsGetCurrentContext();
CGContextClearRect(ctx, rect);
CGPoint center = self.center;
float angle_start = 0;
float angle_end = 0;
for (WYPicChartsObj *objin _dataArray) {
angle_end = 0;
float p = obj.percent;//所有percent和累加为1.0
UIColor *color = obj.fillColor;
angle_end = angle_start + p * M_PI *2 ;
UIBezierPath* ref = [selfaddPath:center start:angle_startend:angle_end color:color];
[_mutablePath addObject:ref];
angle_start = angle_end;
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [[touches allObjects] objectAtIndex:0];
CGPoint point = [touch locationInView:self];
NSInteger index = 0;
for (UIBezierPath* pathin _mutablePath) {
if([path containsPoint:point]){
[delegatepieChartsDidSelectIndex:index];
break;
}
index++;
}
}
@end
//调用
WYPieCharts *pie = [[WYPieChartsalloc] initWithFrame:self.view.bounds];
NSMutableArray *d = [NSMutableArrayarrayWithCapacity:12];
for (int i = 0; i < 12 ; i++) {
WYPicChartsObj *obj = [[WYPicChartsObjalloc] initWithFillcolor:[UIColorcolorWithRed:15 * i / 255.0 green:16 * i / 255.0 blue:17 * i / 255.0 alpha:1.0] percent:1 / 12.0];
[d addObject:obj];
}
pie.dataArray = d;
pie.delegate = self;
[self.view addSubview:pie];
说明:仅仅是实现功能,细节没处理。