问题描述
我编写了一个自定义的UIGestureRecognizer,用一根手指处理旋转。它的设计与Apples UIRotationGestureRecognizer完全相同,并返回相同的值。
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.
现在,我想实现速度,但我无法弄清楚Apple如何定义并计算手势识别器的速度。
有没有人知道Apple如何在UIRotationGestureRecognizer中实现这个?
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?
推荐答案
你必须保留最后的参考触摸位置及其时间戳。
You would have to keep reference of last touch position and it's timestamp.
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;
}
这应该会给你一些速度参考。
This should give you some kind of speed reference.
这篇关于在自定义UIGestureRecognizer中实现速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!