【问题标题】:UITouch touchesMoved Finger Direction and SpeedUITouch 触摸移动的手指方向和速度
【发布时间】:2012-05-03 13:16:51
【问题描述】:

如何在 touchmoved 函数中获取手指运动的速度和方向?

我想获取手指速度和手指方向,并将其应用于 UIView 类方向移动和动画速度。

我阅读了这个链接,但我无法理解答案,此外它没有解释我如何检测方向:

UITouch movement speed detection

到目前为止,我尝试了以下代码:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *anyTouch = [touches anyObject];
    CGPoint touchLocation = [anyTouch locationInView:self.view];
    //NSLog(@"touch %f", touchLocation.x);
    player.center = touchLocation;
    [player setNeedsDisplay];
    self.previousTimestamp = event.timestamp;    
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self.view];
    CGPoint prevLocation = [touch previousLocationInView:self.view];
    CGFloat distanceFromPrevious = [self distanceBetweenPoints:location :prevLocation];
    NSTimeInterval timeSincePrevious = event.timestamp - previousTimestamp;

    NSLog(@"diff time %f", timeSincePrevious);
}

【问题讨论】:

    标签: iphone ios uitouch


    【解决方案1】:

    方向将根据 touchesMoved 中的“location”和“prevLocation”的值确定。具体来说,位置将包含新的触摸点。例如:

    if (location.x - prevLocation.x > 0) {
        //finger touch went right
    } else {
        //finger touch went left
    }
    if (location.y - prevLocation.y > 0) {
        //finger touch went upwards
    } else {
        //finger touch went downwards
    }
    

    现在 touchesMoved 将针对给定的手指移动多次调用。将手指第一次触摸屏幕时的初始值与最终完成移动时的 CGPoint 值进行比较是代码的关键。

    【讨论】:

    【解决方案2】:

    为什么不只是以下作为 obuseme 回应的变体

    -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    
             UITouch *aTouch = [touches anyObject];
             CGPoint newLocation = [aTouch locationInView:self.view];
             CGPoint prevLocation = [aTouch previousLocationInView:self.view];
    
             if (newLocation.x > prevLocation.x) {
                     //finger touch went right
             } else {
                     //finger touch went left
             }
             if (newLocation.y > prevLocation.y) {
                     //finger touch went upwards
             } else {
                     //finger touch went downwards
             }
    }
    

    【讨论】:

    • 别忘了[super touchesMoved:touches withEvent:event]! :D
    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    相关资源
    最近更新 更多