我想跟踪以像素为单位移动的触摸速度/第二
个有想法的朋友
除了 PanGesture 方法
我假设您想知道连续运动之间的速度,而不是一系列运动的平均值。不过,如果您有其他要求,该理论应该很容易适应。
你需要知道三件事:
然后用毕达哥拉斯来计算你的距离,然后除以时间来计算速度。
当您收到touchesMoved事件时,它将为您提供当前和以前的位置。然后,您需要添加的只是时间的度量。
为此,您需要在您的类中使用NSDate属性来帮助计算时间间隔。您可以在 viewDidLoad / viewDidUnload 或类似的地方初始化并释放它。在我的示例中,我的称为lastTouchTime,它被保留,我初始化如下:
self.lastTouchTime = [NSDate date];
我以可预测的方式释放它。
您的touchesMoved事件应如下所示:
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSArray *touchesArray = [touches allObjects];
UITouch *touch;
CGPoint ptTouch;
CGPoint ptPrevious;
NSDate *now = [[NSDate alloc] init];
NSTimeInterval interval = [now timeIntervalSinceDate:lastTouchTime];
[lastTouchTime release];
lastTouchTime = [[NSDate alloc] init];
[now release];
touch = [touchesArray objectAtIndex:0];
ptTouch = [touch locationInView:self.view];
ptPrevious = [touch previousLocationInView:self.view];
CGFloat xMove = ptTouch.x - ptPrevious.x;
CGFloat yMove = ptTouch.y - ptPrevious.y;
CGFloat distance = sqrt ((xMove * xMove) + (yMove * yMove));
NSLog (@"TimeInterval:%f", interval);
NSLog (@"Move:%5.2f, %5.2f", xMove, yMove);
NSLog (@"Distance:%5.2f", distance);
NSLog (@"Speed:%5.2f", distance / interval);
}
抱歉,如果我在任何内存管理方面犯了错误,我仍然对 ObjectiveC 的做事方式不太满意。如果有必要,我相信有人可以纠正它!
祝你好运,冷冻。