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);
}
To draw a line from the current point to a specific point, you call the addLine(to:) method. By default, iOS fills the path with the default foreground color, which is black.
The CGContext type represents a Quartz 2D drawing destination. A graphics context contains drawing parameters and all device-specific information needed to render the paint on a page to the destination, whether the destination is a window in an application, a bitmap image, a PDF document, or a printer.
I know this is an old question, but based on the answer I wrote the following in Swift:
override func drawRect(rect: CGRect) {
super.drawRect(rect)
UIColor.blackColor().setStroke() // update with correct color
let path = UIBezierPath()
path.lineWidth = UIScreen.mainScreen().scale > 1 ? 0.5 : 1
// change the points to what you need them to be
let leftPoint = CGPointMake(0, CGRectGetHeight(rect))
let rightPoint = CGPointMake(CGRectGetWidth(rect), CGRectGetHeight(rect))
path.moveToPoint(leftPoint)
path.addLineToPoint(rightPoint)
path.stroke()
}
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 */
CGContextSetLineWidth(currentContext,5.0f);
/* 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 */
CGContextStrokePath(currentContext);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With