I have to draw a line .I use the below code.My actual need is to draw lines from points that are present in an 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);
}

I receive the context as nil.I receive the following error

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

The array lineGraphPoints has the points that is to be plotted.Can anyone help me out to draw a line graph?

有帮助吗?

解决方案

What you are asking is easily accomplish by enumerating through the array of CGPoint values. Also make sure to override the drawRect: method and add your drawing code there. See the example below for how to use CGPoint Values in a Mutable Array to construct a line in the graphics context.

- (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];
}

I instantiated the mutable array within the drawRect method but you could declare an instance of it in your header file and instantiate wherever you prefer and add your point values to it.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top