Question

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

Was it helpful?

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

OTHER TIPS

Just implement your own rendition of the Pythagorean theorem. For example:

CGPoint translation = CGPointMake(endPoint.x - startPoint.x, endPoint.y - startPoint.y);
CGFloat distance = sqrtf(translation.x * translation.x + translation.y * translation.y);

Or, better, as Rob Mayoff pointed out, use the Math.h hypotf method:

CGFloat distance = hypotf(translation.x, translation.y);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top