Iphone画饼图工具类详解
项目中需要画饼图,在此将工具类添出来:
h文件:
[cpp]
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
@inte易做图ce CLMView : UIView
{
float spaceHeight; //高度
float scaleY ;
NSArray *titleArr ; //文字
NSArray *valueArr; //值
NSArray *colorArr; //颜色
}
@property(nonatomic, assign) float spaceHeight;
@property(nonatomic, assign) float scaleY;
@property(nonatomic, retain) NSArray *titleArr;
@property(nonatomic, retain) NSArray *valueArr;
@property(nonatomic, retain) NSArray *colorArr;
@end
m文件:
[cpp]
#import "CLMView.h"
#define K_PI 3.1415
#define KDGREED(x) ((x) * K_PI * 2)
@implementation CLMView
@synthesize spaceHeight, scaleY;
@synthesize titleArr, valueArr, colorArr;
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.backgroundColor = [UIColor colorWithRed:240.0f/255.0f green:1 blue:1 alpha:1.0];
spaceHeight = 40;
scaleY = 0.4;
}
return self;
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
//cgcontextsets
//抗锯齿
CGContextSetAllowsAntialiasing(context, TRUE);
// int arr[5] = {20, 15, 35, 85 ,60};
float sum = 0;
for(int j=0;j< [valueArr count]; j++)
{
sum += [[valueArr objectAtIndex:j] floatValue];
}
CGContextMoveToPoint(context, 160, 230);
float currentangel = 0;
//饼图
CGContextSaveGState(context);
CGContextScaleCTM(context, 1.0, scaleY);
currentangel = 0;
for(int i = 0; i< [valueArr count]; i++)
{
float startAngle = KDGREED(currentangel);
currentangel += [[valueArr objectAtIndex:i] floatValue] / sum;
float endAngle = KDGREED(currentangel);
//绘制上面的扇形
CGContextMoveToPoint(context, 160, 230);
[[colorArr objectAtIndex:i % [valueArr count]] setFill];
[[UIColor colorWithWhite:1.0 alpha:0.8] setStroke];
CGContextAddArc(context, 160, 230, 150, startAngle, endAngle, 0);
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFill);
//绘制侧面
float starx = cos(startAngle) * 150 +160;
float stary = sin(startAngle) * 150 + 230;
float endx = cos(endAngle) * 150 + 160;
float endy = sin(endAngle) * 150 + 230;
//float starty1 = stary + spaceHeight;
float endy1 = endy + spaceHeight;
if(endAngle < K_PI)
{
//绘制厚度
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, nil, starx, stary);
CGPathAddArc(path, nil, 160, 230, 150, startAngle, endAngle, 0);
CGPathAddLineToPoint(path, nil, endx, endy1);
CGPathAddArc(path, nil, 160, 230 + spaceHeight, 150, endAngle, startAngle, 1);
CGContextAddPath(context, path);
[[colorArr objectAtIndex:i % [valueArr count]] setFill];
[[UIColor colorWithWhite:0.9 alpha:1.0] setStroke];
CGContextDrawPath(context, kCGPathFill);
[[UIColor colorWithWhite:0.1 alpha:0.4] setFill];
&nb
补充:移动开发 , IOS ,