我想有一个类用于在其中呈现简单的图表(没有复杂的东西)。我的想法是/是:
- Sublass an
UIView
--> 让我们称之为Grapher
- 在其中实现我的所有方法 (
drawBarGraph
,drawProgressBar
,drawLineGraph
) - 将其包含在所需的视图控制器中,创建 的实例
Grapher
,调用所需的方法 - 将该实例作为子视图添加到我的主视图中。
让我们跳入一些代码,因为我不知道如何解释这一点。这是grapher.h
:
@interface Grapher : UIView
{
CGContextRef context; //for passing it in via constructor
//UIColor *backgroundColor;
UIColor *graphColor; //foreground color
}
- (id)initWithFrame:(CGRect)frm inContext:(CGContextRef)ctx;
- (void)setGraphColor:(UIColor*)color;
- (void)drawHistogramWithItems:(NSArray*)items;
//- (void)drawLineChartWithItems:(NSArray*)items;
- (void)drawProgressLineWithPercentage:(float)percent;
以及相应的grapher.m
:
@implementation Grapher
- (id)initWithFrame:(CGRect)frm inContext:(CGContextRef)ctx
{
self = [super initWithFrame:frm];
if (self)
{
context = ctx;
}
return self;
}
#pragma Mark main draw methods
- (void)drawHistogramWithItems:(NSArray *)items
{
//[backgroundColor set];
//UIRectFill(frame);
[graphColor set];
int itemWidth = 20;
if (items.count == 0) return;
float max = -1;
for (SFGraphItem *item in items)
if (item.value > max)
max = item.value;
float spacing = (frame.size.width - (itemWidth * items.count)) / (items.count + 1);
float xPos = spacing;
for (int i = 0; i < items.count; i++)
{
CGFloat itemHeight = ((SFGraphItem*)[items objectAtIndex:i]).value / max * frame.size.height;
CGRect bar = CGRectMake(xPos, frame.origin.y + frame.size.height - itemHeight, itemWidth, itemHeight);
CGContextAddRect(context, bar);
CGContextDrawPath(context, kCGPathFill);
xPos += spacing + itemWidth;
}
}
- (void)drawProgressLineWithPercentage:(float)percent
{
//[backgroundColor set];
//UIRectFill(frame);
[graphColor set];
UIRectFill(CGRectMake(frame.origin.x, frame.origin.y, frame.size.width / 100 * percent, frame.size.height));
}
#pragma Mark setters/getters
- (void)setGraphColor:(UIColor *)color
{
graphColor = color;
}
@end
很好很简单。如果我将它子类化为另一个文件中的NSObject
then 子类UIView
(让我们调用它),在那里GraphArea
覆盖,然后传递它就可以了。drawRect
alloc-init
Grapher
UIGraphicsGetCurrentContext()
但我不想要一个“中间观点”。我想子类化UIView
并Grapher
这样做:
Grapher *graph = [[Grapher alloc] initWithFrame:CGRectMake(5, 65, winSize.width - 10, 20)]; //some random frame
[graph setGraphColor:[UIColor redColor]];
[graph drawProgressLineWithPercentage:50];
graph.backgroundColor = [UIColor grayColor];
[someview addSubview:graph];
如果我用CGContextRef
or 这个调用构造函数并尝试在那里获取上下文,它总是为空的。如何在当前上下文中传递?我做错了什么以及如何解决这个问题?
如果我解释得太草率,请告诉我,我会更加努力。
干杯,简。