Drag + Rotation using UIPanGestureRecognizer touch getting off track

后端 未结 2 675
梦如初夏
梦如初夏 2021-01-05 12:35

I am doing some drag and rotation calculations using UIPanGestureRecognizer. The rotation angle is correct, and the drag location is almost correct. The problem is that as y

相关标签:
2条回答
  • 2021-01-05 13:11

    I've finally solved this issue and have it working perfectly. Persistence am I right??

    Here is the code for the solution with a few comments to explain the changes.

    - (void)handlePan:(UIPanGestureRecognizer *)gesture
    {
        if (gesture.state == UIGestureRecognizerStateBegan) {
            // Get the location of the touch in the view we're dragging.
            CGPoint location = [gesture locationInView:dragView];
    
            // Now to fix the rotation we set a new anchor point to where our finger touched. Remember AnchorPoints are 0.0 - 1.0 so we need to convert from points to that by dividing
            [dragView.layer setAnchorPoint:CGPointMake(location.x/dragView.frame.size.width, location.y/dragView.frame.size.height)];
    
    
        } else if (gesture.state == UIGestureRecognizerStateChanged) {
            // Calculate Our New Angle
            CGPoint p1 = button.center;
            CGPoint p2 = dragView.center;
    
            float adjacent = p2.x-p1.x;
            float opposite = p2.y-p1.y;
    
            float angle = atan2f(adjacent, opposite); 
    
            // Get the location of our touch, this time in the context of the superview.
            CGPoint location = [gesture locationInView:self.view];
    
            // Set the center to that exact point, We don't need complicated original point translations anymore because we have changed the anchor point.
            [dragView setCenter:CGPointMake(location.x, location.y)];
    
            // Rotate our view by the calculated angle around our new anchor point.
            [dragView setTransform:CGAffineTransformMakeRotation(angle*-1)];
    
        }
    }
    

    Hope my month+ struggle and solution helps someone else in the future. Happy Coding :)

    0 讨论(0)
  • 2021-01-05 13:14

    Based on touch events https://github.com/kirbyt/KTOneFingerRotationGestureRecognizer

    Helped me to solve similar problem

    0 讨论(0)
提交回复
热议问题