在自定义UIGestureRecognizer中实现速度



我已经编写了一个自定义的UIGestureRecognizer,它可以用一个手指处理旋转。它被设计为与Apples的UIRotationGestureRecognizer完全一样工作,并返回与它相同的值。

现在,我想实现速度,但我不知道苹果是如何定义和计算手势识别器的速度的。有人知道苹果是如何在UIRotationGestureRecognizer中实现这一点的吗?

您必须保留最后一次触摸位置的参考及其时间戳。

double last_timestamp;
CGPoint last_position;

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

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

这应该会给你一些速度参考。

最新更新