Conor Taylor Conor Taylor - 1 year ago 96
iOS Question

Drawing simple lines on iPhone with CoreGraphics

I would like to draw a straight line between where a user touches the screen, and where the touch ends. i need multiple lines, for if the user repeats the touch-drag-release action, and I also need a button to clear all of the lines. So far I have this code below, but once it is called again, I receive the errors: CGContextSetStrokeColor: invalid context 0x0. This error repeats for: CGContextBeginPath, CGContextMoveToPoint, CGContextAddLineToPoint, CGContextDrawPath.

Any ideas?

- (void)drawRect:(CGRect)rect {
c = UIGraphicsGetCurrentContext();

CGFloat black[4] = {0, 0,
0, 1};
CGContextSetStrokeColor(c, black);
CGContextMoveToPoint(c, 100, 100);
CGContextAddLineToPoint(c, 100, 200);

Answer Source

The complete code is as below.

/* Set the color that we want to use to draw the line */ 
[[UIColor brownColor] set];
/* Get the current graphics context */ 
CGContextRef currentContext =UIGraphicsGetCurrentContext();
/* Set the width for the line */
/* Start the line at this point */ 
CGContextMoveToPoint(currentContext,50.0f, 10.0f);
/* And end it at this point */ 
CGContextAddLineToPoint(currentContext,100.0f, 200.0f);
/* Use the context's current color to draw the line */
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download