Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing Straight Lines with Finger on iPhone

Background: I am trying to create a really simple iPhone app that will allow the user to draw multiple straight lines on the screen with their finger.

I'm using these two methods in my UIViewController to capture the coordinates of each line's endpoints.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

Question: I would like the line to show up as soon as touchesEnded has fired and then keep drawing more lines on the screen. How do I do this? I don't necessarily need the code, but I need help with the big picture idea of how to put it together. Also, I'm not a huge fan of xibs and like to do things all programmatically if that affects the answer.

What I've Tried: I've tried using Quartz 2d but it seems in order to use that, you have to do your drawing in the drawRect method of a separate subclassed view. So I would have to create a new view for each line? and then my coordinates would be messed up b/c I'd have to translate the touches positions from the UIViewController to the view.

I've also tried with OpenGL, which I've had a bit more success with (using the GLPaint sample as a template) but OpenGL seems like overkill for just drawing some straight lines on the screen.

like image 517
Trevor Avatar asked Oct 08 '22 09:10

Trevor


1 Answers

You don't need multiple views, and you don't need OpenGL.

Make a subclass of UIView -- call it CanvasView.

Make an object to represent "a line" in your canvas -- it would be a subclass of NSObject with CGPoint properties for start and end.

CanvasView should keep an array of the lines that are in the canvas.

In -[CanvasView drawRect:], loop through the lines in the array, and draw each one.

In -[CanvasView touchesBegan:withEvent:], stash the start point in an instance variable. In -[CanvasView touchesEnded:withEvent:], make a new line with the start and end points, and add it to your array of lines. Call [self setNeedsDisplay] to cause the view to be redrawn.

like image 186
Kurt Revis Avatar answered Oct 12 '22 00:10

Kurt Revis