Pan drag UIView on UIBezierPath curve


This article covers the one of the solution to pan the UIView along the UIBezierPath curve with UIPanGestureRecognizer. It’s code written in Swift 3, Xcode 8.3.2

Let’s look at the output before going into details.

https://machinethinks.com/wp-content/uploads/2017/07/output.gif
output

 

 

 

 

 

 

 

 

 

 

 

Requirement:

There are several examples you can find on stackoverflow on how to animate the UIView on the UIBezierPath. But there are not many examples that show how to move the object along the path with user touch, pan interactions. So here, we discuss the possibility of it.

Limitation:

This code works with the assumption that the bezier curve Path flows in a linear curve. i,e there is continuous increase or decrease  in either X or Y axis while drawing the curve. The output.gif show the sample curve that has continuous increase from start to finish  on Y axis.

How to code:

Let’s draw the UIBezierPath with QuadCurve which takes start point, end point and the control point.

1) Created Quad curve and stored the start point p0, end point p2 and control point p1. We called drawBezierPath()  in viewDidLoad()

bezierPath.move(to: p0)

bezierPath.addQuadCurve(to: p2, controlPoint: p1)

2) emojiView is the view that we are going to drag along the UIbezierPath.

3) In viewDidAppear – we set the emojiView center to the starting point the curve and also store the starting emojiView position.

4) Add the UIPanGestureRecognizer to the view.

5) Now comes the points calculation part. If it takes 1 unit time to draw the beziere path. Below method gets the (x,y) point at the specific time interval between 0 & 1.  Big thanks to Eric Sudan for the idea @ http://ericasadun.com

This method needs to be called twice one for x point and again for y point.

6) Here is the final part on how to drag

First we get the location of the pan in the view. Then calculate the distanceYInRange based on the Y difference of the panned location and the starting Y location. We can obtain the (X,Y) on the bezier curve using getPointAtPercent method. Las step is to change position to emojiView to new location.

The complete code in this article is available at github. For any questions, feel free to comment. Happy coding!!


 

Passionate about learning new things. Loves coding and problem solving. Built apps from scratch on iOS platform with Swift, Objective – C,  HTML 5 / javascript, Cardova, Xamarin using both MVC and MVVM. Coded extensively in .Net and Database technologies before moving to mobile development.

Spends free time playing with my kid and watching TV.