Happy Tuesday, everyone! This week for our tutorial, we welcome our developer Matthieu to the blog. He’s going to walk us through setting up a canvas in Swift with dragging and boundaries.
First set up a class UIViewController:
Next, we are going to set up all the variables we require.
customView : the canvas.
referenceHeight : the height of the canvas.
referenceWidth : the width of the canvas.
marginLeft : position of the canvas on the horizontal axis.
marginTop : position of the canvas on the vertical axis.
fingerXLocation : last known position of the finger of the user on the horizontal axis.
fingerYLocation : last known position of the finger of the user on the vertical axis.
imageXPosition : position of the image in the canvas on the horizontal axis.
imageYPosition : position of the image in the canvas on the vertical axis.
panRec : Pan gesture recognizer attached to the image.
We are then going to setup the view and the variables.
We create the canvas by giving it a size, a position, a background color (useful to check if our image did not go out of its boundaries).
We then create the UIImageView which is going to contain the image and be, itself, in the view mentioned before. We resize the image so it fits in height, if the picture ratio is wider than the canvas, and other, in width if it is taller than the canvas.
We finish the UIImageView creation and attached to it a Pan gesture recognizer which calls the function draggedView.
This function takes care of moving the image around following the finger and keep the image inside the canvas.
If the user just touches the screen, we store the position of his finger and wait for him to move it to start applying and translation.
If the user moved his finger we calculate the vector of translation to move the image accordingly and to this vector apply restriction so the image never goes out of focus.
Finally, we update the finger location for the next vector calculation.