How to draw blur shape using UIPanGestureRecognizer — Swift 5

If you are editing an image and you want to blur only specific part of image wether it is the sensitive info or the unwanted info, this article will help you to achieve this goal. After reading this article, you ll be able to draw a blur shape rectangle using UIPanGestureRecognizer.

Desired result image

We’ ll start off by making a Rectangle class, and we will define some properties inside that class.

We’ ll also override draw(_ rect: CGRect) function so that we can draw our rectangle. Also, we will add a UIPanGestureRecognizer named moveRectangleGesture(_ gesture: UIPanGestureRecognizer) so that we can move the added blur to our desired position.

Notice that we are using += inside the moveRectangleGesture(_ gesture: UIPanGestureRecognizer) function. We are overloading the += operator so that we can assign gesture translation to our drawn rectangle.

Now that we are done with making Rectangle class, its time to draw blur using UIPanGestureRecognizer. We will declare an UIImageView inside our class and will give it proper frame. After that we will assign a pan gesture to that imageView.

We’ve declared a class which have an image which on which we will draw our blur. On that image , we’ve added a panGesture. Also, we’ve declared an array of allRectangles which is of type Rectangle, to draw multiple blurs. Let’s complete the code for our panGesture.

Inside pan(_ gesture: UIPanGestureRecognizer), on .begin state we are creating a rectangle which has no width and height and we are appending it to the rectangles array. Then on .changed state, we are expanding the created rectangle frame along with the movement of our pan gesture. And finally upon .ended state, we add blur to our rectangle.

Adding blur through panGesture can be really helpful when are not sure how much part of an image we want to blur and when the parts to be blurred are not even enough. Through the above approach, we can avoid those problems.

Happy Coding!

iOS Developer — Connect with me www.linkedin.com/in/Muhammad-Abubakar-iOS