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.
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.
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