首先感谢Muh Hon Cheng的PlotCreator程序。
绘图的步骤如下:
CGContextRef ctx =UIGraphicsGetCurrentContext();//获取上下文
UIGraphicsPushContext(ctx);//push上下文
CGContextSetLineWidth(ctx, line_width);//设置线的宽度
CGContextMoveToPoint(ctx,x,y);//将点移动到坐标为x,y的点
CGContextAddLineToPoint(ctx,x1,y1);//将点从(x,y)移动到(x1,y1)
CGContextStrokePath(ctx);//画图
定义类LineChartObject用来存储一个线的全部信息
NSString *title;//标题
NSMutableArray *points;//存储全部点的值的可变数组
UIColor *color; //线的颜色
具体代码如下:
@interface LineChartObject :NSObject
{
NSString *title;
NSMutableArray *points;
UIColor *color;
}
@property (strong,nonatomic)NSString *title;
@property (strong,nonatomic)NSMutableArray *points;
@property (strong,nonatomic)UIColor *color;
@end
@implementation LineChartObject
@synthesize title;
@synthesize points;
@synthesize color;
- (id)init
{
self = [superinit];
if (self) {
points = [[NSMutableArrayalloc]initWithCapacity:0];
}
return self;
}
- (void)dealloc
{
[colorrelease];
[titlerelease];
[pointsremoveAllObjects];
[pointsrelease];
[superdealloc];
}
@end
定义类LineChartView用来显示全部的线
NSMutableArray *LineChartArray; //用来存储LineChartObject
绘制线在 -(void)drawRect:(CGRect)rect;函数中实现具体代码如下:
@interface LineChartView :UIView
{
NSMutableArray *LineChartArray;
}
@property (strong,nonatomic)NSMutableArray *LineChartArray;
@end
@implementation LineChartView
@synthesize LineChartArray;
- (id)initWithFrame:(CGRect)frame
{
self = [superinitWithFrame:frame];
if (self) {
[selfsetBackgroundColor:[UIColorwhiteColor]];
LineChartArray = [[NSMutableArrayalloc]initWithCapacity:0];
}
return self;
}
- (void)drawRect:(CGRect)rect
{
float line_width = 4;
CGContextRef ctx =UIGraphicsGetCurrentContext();
UIGraphicsPushContext(ctx);
NSLog(@"LineChartArray = %@",LineChartArray);
for (int i =0; i<=10; i++) {
UILabel *label = [[UILabelalloc]initWithFrame:CGRectMake(0,4+100*i, 50, 50)];
[label setBackgroundColor:[UIColorclearColor]];
label.text = [NSStringstringWithFormat:@"%d",(100-10*i)];
[selfaddSubview:label];
}
for (LineChartObject *objectin LineChartArray)
{
for (int i =0; i<[[object points]count]; i++) {
CGContextSetLineWidth(ctx, line_width);
[object.colorset];
float y = [[object.pointsobjectAtIndex:i]floatValue];
CGContextMoveToPoint(ctx, (i+1)*76,1004-(10*y));
NSLog(@"x = %d,y = %f",(i+1)*76,1004-(10*y));
if (i < [[object points]count]-1) {
float y1 = [[object.pointsobjectAtIndex:(i+1)]floatValue];
CGContextAddLineToPoint(ctx,(i+2)*76,1004-(10*y1));
}
CGContextStrokePath(ctx);
}
NSString *title = [object title];
UIFont *font = [UIFontfontWithName:@"GeezaPro"size:40];
[titledrawInRect:CGRectMake(([[objectpoints]count]*76),1004-(10*[[object.pointsobjectAtIndex:([[object points]count]-1)]floatValue])-50,50,50)withFont:font];
}
}
- (void)dealloc
{
[LineChartArrayrelease];
[superdealloc];
}
@end
文中如有错误之处请各位大神多多批评。