Reputation: 201
I want to draw a line with different colors using CGContext.
This is my code
CGSize size = CGSizeMake(200, 200);
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGContextMoveToPoint(context, 1, 1);
CGContextBeginPath(context);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextAddLineToPoint(context, 50, 50);
CGContextAddLineToPoint(context, 100, 50);
CGContextStrokePath(context);
CGContextBeginPath(context);
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextAddLineToPoint(context, 200, 100);
CGContextStrokePath(context);
I am trying this code, its returns error:
<Error>: CGContextAddLineToPoint: no current point.
Upvotes: 0
Views: 1304
Reputation: 2768
Following code maybe help you:
CGSize size = CGSizeMake(200, 200);
//UIGraphicsBeginImageContextWithOptions(size, NO, 0); //comment this line, if you want a image, see bottom two line.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGContextBeginPath(context);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextMoveToPoint(context, 1, 1); //MoveToPoint First
CGContextAddLineToPoint(context, 50, 50);
CGContextAddLineToPoint(context, 100, 50);
CGContextStrokePath(context);
CGContextBeginPath(context);
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextMoveToPoint(context, 100, 50); //MoveToPoint First
CGContextAddLineToPoint(context, 200, 100);
CGContextStrokePath(context);
//UIImage* resultImage = UIGraphicsGetImageFromCurrentImageContext(); //if you just need a image
//UIGraphicsEndImageContext(); //match UIGraphicsBeginImageContextWithOptions, if need a image
Upvotes: 0
Reputation: 3441
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, rect);
CGContextSetLineWidth(context, 2.0);
CGContextBeginPath(context);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextMoveToPoint(context, 1, 1);
CGContextAddLineToPoint(context, 100, 100);
CGContextStrokePath(context); // and draw blue line
CGContextBeginPath(context);
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextMoveToPoint(context, 100, 100);
CGContextAddLineToPoint(context, 200, 100);
CGContextStrokePath(context); // draw red line
Upvotes: 2