在自定义 UIGestureRecognizer 中实现速度

sim*_*nbs 3 iphone velocity uigesturerecognizer

我编写了一个自定义 UIGestureRecognizer,它可以用一根手指处理旋转。它的设计工作方式与 Apple 的 UIRotationGestureRecognizer 完全相同,并返回相同的值。

现在,我想实现速度,但我无法弄清楚苹果如何定义和计算手势识别器的速度。有谁知道 Apple 如何在 UIRotationGestureRecognizer 中实现此功能?

Rok*_*arc 6

您必须保留上次触摸位置及其时间戳的引用。

double last_timestamp;
CGPoint last_position;
Run Code Online (Sandbox Code Playgroud)

然后你可以做类似的事情:

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    last_timestamp = CFAbsoluteTimeGetCurrent();

    UITouch *aTouch = [touches anyObject];
    last_position = [aTouch locationInView: self];
}


-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    double current_time = CFAbsoluteTimeGetCurrent();

    double elapsed_time = current_time - last_timestamp;

    last_timestamp = current_time;

    UITouch *aTouch = [touches anyObject];
    CGPoint location = [aTouch locationInView:self.superview];

    CGFloat dx = location.x - last_position.x;
    CGFloat dy = location.y - last_position.y;

    CGFloat path_travelled = sqrt(dx*dx+dy*dy);

    CGFloat sime_kind_of_velocity = path_travelled/elapsed_time;

    NSLog (@"v=%.2f", sime_kind_of_velocity);

    last_position = location;
}
Run Code Online (Sandbox Code Playgroud)

这应该可以为您提供某种速度参考。

  • 请注意:使用 event.timestamp 或 touch.timestamp 属性而不是 CFAbsoluteTimeGetCurrent() 更精确。 (4认同)