Search code examples
objective-ctouchdrawrectuitouch

find the distance between two CG points?


I am using these methods and these variables

CGPoint touchBegan;
CGPoint touchEnd;

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

}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

}

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

}

But I can not get the distance between two points. For example draw a line with your finger and get the distance between a CGPoint touchBegan and CGPoint touchEnd

Any help is appreciated thanks


Solution

  • It doesn't seem to exist any method or function that do this directly, you must take the difference of the two points coordinates and use pythagorean theorem:

    CGPoint touchBegan;
    CGPoint touchEnd;
    
    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
        UITouch* touch= [touches anyObject];
        touchBegan= [touch locationInView: self.view];
    }
    
    - (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch* touch= [touches anyObject];
        touchEnd= [touch locationInView: self.view];
        CGFloat dx= touchBegan.x - touchEnd.x;
        CGFloat dy= touchBegan.y - touchEnd.y;
        CGFloat distance= sqrt(dx*dx + dy*dy);
        < Do stuff with distance >
    }