Objective c 绘制线图的上下文0x0无效

Objective c 绘制线图的上下文0x0无效,objective-c,graph,cgcontext,linegraph,Objective C,Graph,Cgcontext,Linegraph,我必须画一条线。我使用下面的代码。我的实际需要是从NSMutableArray - (void)drawLineGraph:(NSMutableArray *)lineGraphPoints { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor); CGContextS

我必须画一条线。我使用下面的代码。我的实际需要是从
NSMutableArray

   - (void)drawLineGraph:(NSMutableArray *)lineGraphPoints
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
    CGContextSetLineWidth(context, 1.0f);
    CGContextMoveToPoint(context, 10, 10);
    CGContextAddLineToPoint(context, 100, 50);
    CGContextStrokePath(context);
}
我收到的上下文为nil

Aug  3 10:46:04 ABC-Mac-mini.local Sample[2077] <Error>: CGContextSetStrokeColorWithColor: invalid context 0x0
Aug  3 10:46:04 ABC-Mac-mini.local Sample[2077] <Error>: CGContextSetLineWidth: invalid context 0x0
Aug  3 10:46:04 ABC-Mac-mini.local Sample[2077] <Error>: CGContextMoveToPoint: invalid context 0x0
Aug  3 10:46:04 ABC-Mac-mini.local Sample[2077] <Error>: CGContextAddLineToPoint: invalid context 0x0
Aug  3 10:46:04 ABC-Mac-mini.local Sample[2077] <Error>: CGContextDrawPath: invalid context 0x0
Aug 3 10:46:04 ABC-Mac-mini.local示例[2077]:CGContextSetStrokeColorWithColor:无效上下文0x0
八月3日10:46:04 ABC-Mac-mini.local样本[2077]:CGContextSetLineWidth:无效上下文0x0
八月3日10:46:04 ABC-Mac-mini.local样本[2077]:CGContextMoveToPoint:无效上下文0x0
八月3日10:46:04 ABC-Mac-mini.local样本[2077]:CGContextAddLineToPoint:无效上下文0x0
八月3日10:46:04 ABC-Mac-mini.local样本[2077]:CGContextDrawPath:无效上下文0x0

数组
lineGraphPoints
包含要绘制的点。有人能帮我绘制一个线图吗?

通过枚举CGPoint值数组可以轻松完成您的要求。还要确保重写drawRect:方法并在其中添加图形代码。有关如何在可变数组中使用CGPoint值在图形上下文中构造线,请参见下面的示例

- (void)drawRect:(CGRect)rect {
    NSMutableArray *pointArray = [[NSMutableArray alloc] initWithObjects:
    [NSValue valueWithCGPoint:CGPointMake(10, 10)],
    [NSValue valueWithCGPoint:CGPointMake(10, 10)],
    [NSValue valueWithCGPoint:CGPointMake(12, 16)],
    [NSValue valueWithCGPoint:CGPointMake(20, 22)],
    [NSValue valueWithCGPoint:CGPointMake(40, 100)], nil];

    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
    CGContextSetLineWidth(context, 1.0f);

    for (NSValue *value in pointArray) {
    CGPoint point = [value CGPointValue];

        if ([pointArray indexOfObject:value] == 0) {
            CGContextMoveToPoint(context, point.x, point.y);
        } else {
            CGContextAddLineToPoint(context, point.x, point.y);
        }
    }

    CGContextStrokePath(context);
    [pointArray release];
}

我在drawRect方法中实例化了可变数组,但您可以在头文件中声明它的一个实例,并在您喜欢的任何地方实例化,并向其中添加点值。

此函数是从
drawRect:
中调用的吗?如果不是,则
UIGraphicsGetCurrentContext()
将返回nil。@H2CO3:谢谢,工作正常