我希望能够追踪触摸移动的速度,单位为像素/秒。
有没有任何人有这方面的想法?
除了PanGesture方法。
我希望能够追踪触摸移动的速度,单位为像素/秒。
有没有任何人有这方面的想法?
除了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的做法还不是非常熟悉。如果有必要,我相信有人可以纠正它!
祝你好运,Freezing。