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);
CGContextBeginPath(c);
CGContextMoveToPoint(c, 100, 100);
CGContextAddLineToPoint(c, 100, 200);
CGContextStrokePath(c);
}
I know this is an old question, but based on the answer I wrote the following in Swift:
The Problem is that
UIGraphicsGetCurrentContext()
will return a null-reference. If you want to draw into an UIImage you can get the CGContextRef as follows:now calling
UIGraphicsGetCurrentContext()
will not longer return a null-reference.... drawing goes here
The complete code is as below.
Swift 3
Here is a full example for drawing lines (a grid) in a separate image and then added this image (as an overlay) to an existing image, in this case called 'boardImage' .
You haven't defined the type for
c
: