How to move an UIView along a curved CGPath according to user dragging the view

| | August 5, 2015

I’m trying to build a interface that the user can move his finger around the screen an a list of images moves along a path. The idea is that the images center nevers leaves de path.

Most of the things I found was about how to animate using CGPath and not about actually using the path as the track to a user movement.

I need to objects to be tracked on the path even if the user isn’t moving his fingers over the path.

For example (image bellow), if the object is at the beginning of the path and the user touches anywhere on the screen and moves his fingers from left to right I need that the object moves from left to right but following the path, that is, going up as it goes to the right towards the path’s end.

This is the path I’ve draw, imagine that I’ll have a view (any image) that the user can touch and drag it along the path, there’s no need to move the finger exactly over the path. If the user move from left to right the image should move from left to right but going up if need following the path.

The curved path

This is how I’m creating the path:

   CGPoint endPointUp = CGPointMake(315, 124);
    CGPoint endPointDown = CGPointMake(0, 403);
    CGPoint controlPoint1 = CGPointMake(133, 187);
    CGPoint controlPoint2 = CGPointMake(174, 318);

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, endPointUp.x, endPointUp.y);
    CGPathAddCurveToPoint(path, NULL, controlPoint1.x, controlPoint1.y, controlPoint2.x, controlPoint2.y, endPointDown.x, endPointDown.y);

Any idead how can I achieve this?

One Response to “How to move an UIView along a curved CGPath according to user dragging the view”

  1. Neal Tibrewala on November 30, -0001 @ 12:00 AM

    Try using the CAKeyframeAnimation class.

    Also see this question: CGPath Animation

    However, based on your description, wanting an animation seems like it might not be what you want. IF the user is going to have ‘live’ control on the left/right slide being the location of the subview on the path, you might want to simply calculate the x/y of the path programatically, and apply the x/y values based only on the user’s touches x value.

    So, try using the NSBezierPath class to create your paths, then flatten them by calling bezierPathByFlatteningPath, finally, upon a touch that you want to update the view with, walk through the flattened path by looking at each ‘elementAtIndex:associatedPoints’ until you find the first one greater than your X value. The X/Y of that point will be the point you want to place your object.

Leave a Reply