检测用户触摸移动方向?

时间:2016-06-10 07:10:51

标签: ios drawing core-graphics uibezierpath uitouch

我使用UIBezierPath绘制了字母A.它有三个方向,演示用户将如何绘制此字母表。有没有办法检查用户触摸移动是否在同一方向?

enter image description here

1 个答案:

答案 0 :(得分:1)

我推荐UIPanGestureRecognizer。它将为您提供当前位置,从起点的平移和当前速度。如果你跟踪速度,你会知道它是否与之前的速度相匹配。

您可以使用-[UIBezierPath containsPoint:]来确定手势是否仍在A中。

像这样:

- (void)panRecognizerFired:(UIPanGestureRecognizer *)panRecognizer {
    switch (panRecognizer.state) {
        case UIGestureRecognizerStatePossible:
        {
            // ignore it until it changes to UIGestureRecognizerStateBegan
            return;
        }
        case UIGestureRecognizerStateBegan:
        {
            // handle gesture start here

            // change this to a break if you want a beginning touch to be processed
            // the same as a movement
            return;
        }
        case UIGestureRecognizerStateEnded:
        {
            // handle gesture end here - clean up and undo whatever happened
            // in UIGestureRecognizerStateBegan, show a new controller or something, etc

            // change this to a break if you want an ending touch to be processed
            // the same as a movement
            return;
        }
        case UIGestureRecognizerStateFailed:
        case UIGestureRecognizerStateCancelled:
        {
            // abort! undo everything here
            return;
        }
        default:
            // it moved! break to process that movement
            break;
    }

    CGPoint location = [panRecognizer locationInView:self.theViewThatHasTheLetterAInIt];
    CGPoint translation = [panRecognizer translationInView:self.theViewThatHasTheLetterAInIt];
    CGPoint velocity = [panRecognizer velocityInView:self.theViewThatHasTheLetterAInIt];

    BOOL isLocationInsidePath = [self.letterABezierPath containsPoint:location];

    // make decisions based on isLocationInsidePath and velocity here...
}

要确保此手势仅允许在正确的数字附近开始,请使自己符合UIGestureRecognizerDelegate协议并设置self.panGestureRecognizer.delegate = self。然后您可以使用以下方法限制起始位置:

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer == self.panGestureRecognizer) {
        CGPoint location = [gestureRecognizer locationInView:self.theViewThatHasTheLetterAInIt];

        // implement this property to return the center of the 1, 2, or 3 circle
        CGPoint targetCenter = self.currentTargetCenter;

        CGFloat distanceX = location.x - targetCenter.x;
        CGFloat distanceY = location.y - targetCenter.y;
        CGFloat distanceDiagonalSquared = (distanceX * distanceX) + (distanceY * distanceY);

        const CGFloat maxDistance = 20.f;

        return (distanceDiagonalSquared <= maxDistance * maxDistance);
    }

    return YES;
}