David
David

Reputation: 2620

iPhone - Drawing on the screen in response to touch event

I'm working on an assignment for a class, and need a bit of direction. I'm working with an app that translates a touch event, and subsequent finger dragging, into a drawing on the screen. I need to figure out how to save each drawing in an array, and remove them all in response to a shake event.

It's pretty basic - there is a HomeViewController (UIViewController), and a DoodleView (UIView) that occupies the window. The HomeViewController has a doodleview property, and in the viewDidLoad method, creates an instance, assigns it to self.doodleview, then calls addSubview. The touchesBegan, touchesMoved, and touchesEnded methods belong to the doodleview class. Right now, each click and drag removes the previous one.

My initial stab at saving them, was to create an NSMutableArray "doodleViews" property of HomeViewController, thinking that each touchesBegan event was creating a new instance of doodleView, and just calling addSubview on the last element of that array. This didn't work, and I don't know why. Any tips are appreciated.

Here is a snippet from HomeViewController:

- (void)viewDidLoad {
    [super viewDidLoad];

    CGRect window = [[UIScreen mainScreen] bounds];
    self.doodleView = [[DoodleView alloc] initWithFrame:window];

    CircleGestureRecognizer *recognizer = [[CircleGestureRecognizer alloc] initWithTarget:self action:@selector(handleCircleRecognizer:)]; 
    [self.doodleView addGestureRecognizer:recognizer];

    [self.view addSubview:self.doodleView];

}

Here is a snippet from DoodleView:

- (void) touchesBegan:(NSSet *) touches withEvent:(UIEvent *) event
{
    NSLog(@"touches began");

    path = [UIBezierPath bezierPath];   
    path.lineWidth = 15.0f;
    path.lineCapStyle = kCGLineCapRound;
    path.lineJoinStyle = kCGLineJoinRound;

    UITouch *touch = [touches anyObject];
    [path moveToPoint:[touch locationInView:self]];
}

- (void) touchesMoved:(NSSet *) touches withEvent:(UIEvent *) event
{
    UITouch *touch = [touches anyObject];
    [path addLineToPoint:[touch locationInView:self]];
    [self setNeedsDisplay];
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    [path addLineToPoint:[touch locationInView:self]];
    [self setNeedsDisplay];
}

Upvotes: 1

Views: 1126

Answers (1)

NJones
NJones

Reputation: 27147

You'll probably want to save your UIBezierPath *path to an NSMutableArray in the touchesEnded method. Then in your drawing code iterate through the array and draw each path.

When there's a shake simply removeAllObjects from that array.

Upvotes: 0

Related Questions