以任何角度滑动检测

时间:2011-10-22 23:20:15

标签: ios gesture-recognition

有什么方法可以在任何角度检测iPhone中的滑动吗? UISwipeGestureRecognizer似乎只有4个方向 如果我这样滑动:

\
 \
  \
   X

我希望它能给我60度的东西,而不仅仅是UISwipeGestureRecognizer 我怎么能这样做?

2 个答案:

答案 0 :(得分:8)

您可以使用UIPanGestureRecognizer。当您检测到Ended状态时,您可以获得速度。速度分为x和y分量。您可以使用x和y分量来计算斜率m。

  

m =Δy/Δx

由斜率m定义的线相对于x轴的角度定义如下:

  

= arctan(m)

类似的东西:

- (void)didPan:(UIPanGestureRecognizer*)recognizer {
    switch (recognizer.state) {
        case UIGestureRecognizerStateBegan:
            ...
            break;

        case UIGestureRecognizerStateEnded:
            CGPoint velocity = [recognizer velocityInView:[recognizer.view superview]];
            // If needed: CGFloat slope = velocity.y / velocity.x;
            CGFloat angle = atan2f(velocity.y, velocity.x);
            ...
            break;
    }
}

答案 1 :(得分:3)

您可以检测触摸的开始和停止,并用两点计算角度。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
//global CGPoint.
    //this should be it's GLOBAL coordinates, not just relative to the view    
    startPoint=[[touches anyObject] locationInView:self.superview.superview];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    //global CGPoint
    endPoint=[[touches anyObject] locationInView:self.superview.superview];
}

要计算它们之间的角度,您可以使用以下内容:

static inline CGFloat angleBetweenLinesInRadians(CGPoint line1Start, CGPoint line1End, CGPoint line2Start, CGPoint line2End) {

    CGFloat a = line1End.x - line1Start.x;
    CGFloat b = line1End.y - line1Start.y;
    CGFloat c = line2End.x - line2Start.x;
    CGFloat d = line2End.y - line2Start.y;

    CGFloat line1Slope = (line1End.y - line1Start.y) / (line1End.x - line1Start.x);
    CGFloat line2Slope = (line2End.y - line2Start.y) / (line2End.x - line2Start.x);

    CGFloat degs = acosf(((a*c) + (b*d)) / ((sqrt(a*a + b*b)) * (sqrt(c*c + d*d))));
    return (line2Slope > line1Slope) ? degs : -degs;    
}
//This code came from someone else and I don't remember who to give credit to.

因此,要找到水平线的角度,你可以做类似的事情

CGFloat angle=angleBetweenLinesInRadians(startPoint, endPoint, startPoint, CGPointMake(startPoint.x + 10, startPoint.y));

这就是这样的角度

________
\ this angle
 \
  \
   x

希望这有帮助

编辑 更好的方法

你可以做的是UIGestureRecognizer的子类

#import <UIKit/UIGestureRecognizerSubclass.h>

然后实现这些方法

- (void)reset;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;

其中每个用于确定和设置手势的状态属性。

这里有一个完整的例子: http://developer.apple.com/library/ios/#documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/GestureRecognizers/GestureRecognizers.html