Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement velocity in custom UIGestureRecognizer

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?

like image 987
simonbs Avatar asked Dec 27 '25 16:12

simonbs


1 Answers

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.

like image 94
Rok Jarc Avatar answered Dec 31 '25 18:12

Rok Jarc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!