2

I have written a custom UIGestureRecognizer which handles rotations with one finger. It is designed to work exactly like Apples UIRotationGestureRecognizer and return the same values as it does.

Now, I would like to implement the velocity but I cannot figure out how Apple defines and calculates the velocity for the gesture recognizer. Does anybody have an idea how Apple implements this in the UIRotationGestureRecognizer?

simonbs
  • 7,932
  • 13
  • 69
  • 115
  • 1
    I believe it uses touhcesMoved and a NSTimer to calculate such. I've tried it once but it's very hard to achieve a good result. But I think this is the way to go. – Raphael Ayres Mar 07 '12 at 14:34

1 Answers1

5

You would have to keep reference of last touch position and it's timestamp.

double last_timestamp;
CGPoint last_position;

Then you could do something like:

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

This should give you some kind of speed reference.

Rok Jarc
  • 18,765
  • 9
  • 69
  • 124
  • 4
    Just a note: it is more precise to use event.timestamp or touch.timestamp properties instead of CFAbsoluteTimeGetCurrent(). – Pavel Alexeev Aug 04 '13 at 18:18