绘制一条直线iOS

我正在用这个代码绘制一条直线(很明显用户触摸),我需要从起点显示直线,直到用户从起始点像橡皮筋一样保持触摸(而不是结束触摸)随手指移动。 我可能忽略了一些我需要修改的东西来创build必要的效果。 任何想法?

注:我在一个视图控制器。

- (void) drawLine:(UIPanGestureRecognizer *)sender { NSLog(@"Sender : %@", sender); CGPoint currentPoint; //CGAffineTransformMakeScale(lastScale, lastScale); if([(UIPanGestureRecognizer *)sender state] == UIGestureRecognizerStateBegan || [(UIPanGestureRecognizer *)sender state] == UIGestureRecognizerStateChanged) { currentPoint = [(UIPanGestureRecognizer *)sender locationInView:imgView]; previousPoint = currentPoint; } if([(UIPanGestureRecognizer *)sender state] == UIGestureRecognizerStateChanged) { touchedPoint = [(UIPanGestureRecognizer *)sender locationInView:imgView]; [imgView setNeedsDisplay]; } if([(UIPanGestureRecognizer *)sender state] == UIGestureRecognizerStateEnded) { currentPoint = [(UIPanGestureRecognizer *)sender locationInView:imgView]; imgView.image = [self drawLineFromPoint:previousPoint toPoint:currentPoint image:imgView.image]; previousPoint = currentPoint; } } 

这是[frompoint:topoint:]的方法

 UIGraphicsBeginImageContext(imgView.frame.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSaveGState(context); CGContextTranslateCTM(context, 0.0, imgView.frame.size.height); CGContextScaleCTM(context, 1.0, -1.0); CGContextSetShouldAntialias(context, YES); CGContextSetLineWidth(context, 1.0f); CGContextSetRGBStrokeColor(context, 0.7, 0.7, 0.7, 1.0); CGContextMoveToPoint(context, fromPoint.x, fromPoint.y); CGContextAddLineToPoint(context, toPoint.x, toPoint.y); CGContextDrawPath(context, kCGPathStroke); CGContextRestoreGState(context); NSLog(@"frompoint.x : %f, frompoint.y : %f",fromPoint.x, fromPoint.y ); NSLog(@"topoint.x : %f, topoint.y : %f", toPoint.x, toPoint.y); UIImage *ret = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); 

DrawingApp这是一个我发现的样例项目,

另一种方法是,正如Lefteris在评论中提出的那样,在UIView中,覆盖触摸开始,移动和结束。 并使用drawRect绘制线条。 该线将拖动到您目前的触摸位置。