简体   繁体   中英

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

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM