我正在 iPhone 应用程序中创建一个饼图,它工作正常,但我还想显示每个部分的百分比,例如 17% 25% 等。
我正在使用以下代码
-(void)createGraph
{
PieClass *myPieClass=[[PieClass alloc]initWithFrame:CGRectMake(50,440,320,230)];
myPieClass.backgroundColor=[UIColor clearColor];
myPieClass.itemArray=[[NSArray alloc]initWithObjects:valueOne,valueTwo,valueThree,valueFour, nil];
myPieClass.myColorArray=[[NSArray alloc]initWithObjects:[UIColor blueColor],[UIColor redColor],[UIColor greenColor],[UIColor brownColor], nil];
myPieClass.radius=100;
[self.view addSubview:myPieClass];
}
馅饼类
#import <UIKit/UIKit.h>
@interface PieClass : UIView
{
NSArray* itemArray;
NSArray* myColorArray;
int radius;
}
@property(nonatomic,retain)NSArray* itemArray;
@property(nonatomic,retain)NSArray* myColorArray;
@property(nonatomic,assign) int radius;
@end
#import "PieClass.h"
@implementation PieClass
@synthesize itemArray,myColorArray,radius;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
// 仅覆盖 drawRect: 如果您执行自定义绘图。// 空实现会对动画期间的性能产生不利影响。
- (void)drawRect:(CGRect)rect
{
// Drawing code
int c=[itemArray count];
CGFloat angleArray[c];
CGFloat offset;
int sum=0;
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetAllowsAntialiasing(context, false);
CGContextSetShouldAntialias(context, false);
for(int i=0;i<[itemArray count];i++)
sum+=[[itemArray objectAtIndex:i] intValue];
for(int i=0;i<[itemArray count];i++)
{
angleArray[i]=(float)(([[itemArray objectAtIndex:i] intValue])/(float)sum)*(2*3.14); // in radians
CGContextMoveToPoint(context, radius, radius);
if(i==0)
CGContextAddArc(context, radius, radius, radius, 0,angleArray[i], 0);
else
CGContextAddArc(context, radius, radius, radius,offset,offset+angleArray[i], 0);
offset+=angleArray[i];
CGContextSetFillColorWithColor(context, ((UIColor *)[myColorArray objectAtIndex:i]).CGColor);
CGContextClosePath(context);
CGContextFillPath(context);
}
}