【问题标题】:invalid context 0x0 for drawing line graph绘制折线图的无效上下文 0x0
【发布时间】:2013-08-03 05:35:25
【问题描述】:

我必须画一条线。我使用下面的代码。我的实际需要是从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

数组lineGraphPoints 有要绘制的点。谁能帮我画个折线图?

【问题讨论】:

  • 这个函数是从drawRect:内部调用的吗?如果不是,那么UIGraphicsGetCurrentContext() 将返回 nil。
  • @H2CO3 :谢谢,它工作正常

标签: objective-c graph cgcontext linegraph


【解决方案1】:

您的问题很容易通过枚举 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 方法中实例化了可变数组,但您可以在头文件中声明它的一个实例,并在您喜欢的任何地方实例化并将您的点值添加到其中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多