3

I am developing a program which identifies a rectangle in an image and draws a path on the border of that identified rectangle. Now I want to reposition that path in case if it is not on the exact position. For an example look at this image

enter image description here

In cases like this i need to drag the corners of the path and reposition it as it fits the rectangle.

To draw the path I used CAShapeLayer and UIBezierPath. Here is the code I used to draw the path.

// imgView is the UIImageView which contains the image with the rectangle

let line: CAShapeLayer = CAShapeLayer();
line.frame = imgView.bounds; 
let linePath: UIBezierPath = UIBezierPath();

linePath.moveToPoint(CGPointMake(x1, y1);
linePath.addLineToPoint(CGPointMake(x2, y2);
linePath.addLineToPoint(CGPointMake(x3, y3);
linePath.addLineToPoint(CGPointMake(x4, y4);
linePath.addLineToPoint(CGPointMake(x1, y1);
linePath.closePath();

line.lineWidth = 5.0;
line.path = linePath.CGPath;
line.fillColor = UIColor.clearColor().CGColor;
line.strokeColor = UIColor.blueColor().CGColor;

imgView.layer.addSublayer(line);

The thing is I tried to add a gesture to UIBezierPath. But there is nothing like that as I noticed. Couldn't find anything regarding this. So can someone please let me know a way to get my work done. Any help would be highly appreciated.

Hanushka Suren
  • 723
  • 3
  • 10
  • 32

1 Answers1

2

You are right that there is no way to attach a gesture recognizer to a UIBezierPath. Gesture recognizers attach to UIView objects, and a UIBezierPath is not a view object.

There is no built-in mechanism to do this. You need to do it yourself. I would suggest building a family of classes to handle it. Create a rectangle view class. It would use a bezier path internally, as well as placing 4 corner point views on the vertexes and installing pan gesture recognizers each corner point view.

Note that Cocoa rectangles (CGRects) can't be rotated. You'll need to use a series of connected line segments and write logic that forces it to stay square.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Thanks for the suggestion Duncan. I will try it out. btw Thanks again for the quick response and sorry for being late to respond to your answer. cheers – Hanushka Suren Mar 18 '16 at 07:04