使用CoreGraphics在iPhone上绘制简单的线条

Con*_*lor 9 cocoa-touch drawing core-graphics ios

我想在用户触摸屏幕的位置和触摸结束的位置之间绘制一条直线.我需要多行,因为如果用户重复触摸 - 拖动 - 释放动作,我还需要一个按钮来清除所有行.到目前为止,我在下面有这个代码,但是一旦再次调用它,我收到错误:CGContextSetStrokeColor:无效的上下文0x0.此错误重复:CGContextBeginPath,CGContextMoveToPoint,CGContextAddLineToPoint,CGContextDrawPath.

有任何想法吗?

- (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);
}
Run Code Online (Sandbox Code Playgroud)

小智 21

完整的代码如下.

/* 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);
Run Code Online (Sandbox Code Playgroud)