Search code examples
xcodedrawingtouchtouchesmoved

Drawing with touchesMoved


I'm trying to create code for drawing what the user draws with his finger. I used the following code for this:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    if ([touch tapCount] == 2) {
    [myImage setHidden:YES];
}
CGPoint currentTouch = [touch locationInView:self.view];
if (currentTouch.x >10 && currentTouch.x < 300 && currentTouch.y >245 && currentTouch.y < 440) {
CGRect myImageRect = CGRectMake(currentTouch.x, currentTouch.y, 5.0f, 5.0f); 
myImage = [[UIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage imageNamed:@"dot.png"]];
[self.view addSubview:myImage];
}

But the problem is that the touchesMoved doesn't get called every single pixel, so there is a big gap between every point and the next. So I need to somehow fill those gaps. Can someone help me do that with some code?

Thanks in advance.


Solution

  • No need for an answer anymore, I answered my own question :p

    For anyone who wants the answer, though, here's the code:

    UITouch *touch = [touches anyObject];
    currentTouch = [touch locationInView:self.view];
    
    if (currentTouch.x >10 && currentTouch.x < 300 && currentTouch.y >245 && currentTouch.y < 440) {
    CGRect myImageRect = CGRectMake(currentTouch.x, currentTouch.y, 5.0f, 5.0f); 
    myImage = [[UIImageView alloc] initWithFrame:myImageRect];
    [myImage setImage:[UIImage imageNamed:@"dot.png"]];
        myImage.tag = tag;
    [self.view addSubview:myImage];
    [myImage release];
        if (!CGPointEqualToPoint(lastTouch, CGPointMake(0, 0))) { 
            CGPoint nextPoint;
                for (double h = 0.0; h<25.0; h++) {
                double blend = h/25;
                nextPoint.x = currentTouch.x + (blend * (lastTouch.x - currentTouch.x));
                nextPoint.y = currentTouch.y + (blend * (lastTouch.y - currentTouch.y));
                myImageRect = CGRectMake(nextPoint.x, nextPoint.y, 5.0f, 5.0f);
                myImage = [[UIImageView alloc] initWithFrame:myImageRect];
                [myImage setImage:[UIImage imageNamed:@"dot.png"]];
                    myImage.tag = tag;
                [self.view addSubview:myImage];
                [myImage release];
        }
    
        }
    lastTouch = currentTouch;
    }
    }
    

    I added a point called last touch to record the last point, and then a (for) loop to fill the spaces between the current point and the last one.