找到两个CG点之间的距离?

时间:2013-06-24 00:28:03

标签: objective-c touch drawrect uitouch

我正在使用这些方法和这些变量

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 {

}

但我无法得到两点之间的距离。例如,用手指画一条线,得到CGPoint touchBegan和CGPoint touchEnd之间的距离

感谢任何帮助

2 个答案:

答案 0 :(得分:4)

似乎不存在直接执行此操作的任何方法或函数,您必须使用两点坐标的差异并使用毕达哥拉斯定理:

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

答案 1 :(得分:2)

只需实现自己Pythagorean theorem的演绎。例如:

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

或者,更好的是,正如Rob Mayoff指出的那样,使用Math.h hypotf方法:

CGFloat distance = hypotf(translation.x, translation.y);