Search code examples
iosobjective-cuiviewcashapelayercgpath

Preserve CAShapeLayer's lineWidth in a zoomable UIView


I have a custom UIView, which has a UIImageView as its' subview to display an image and a CAShapeLayer as a sublayer to draw on it. The UIView is zoomable, I use a UIPinchGestureRecognizer to zoom in and out of the view. I can draw straight lines on the view using a CGPathRef. The problem is, when I pinch to zoom the view, the lines I draw also zoom and become thick. How to zoom in the view, keeping the lines thin?

Before zooming (green lines are the ones I draw):

enter image description here

And when I zoom:

enter image description here

What I want is, the lines to be as thin as they were before I zoomed in. I tried to:

CGMutablePath path = CGPathCreateMutable();

//line drawing code here

//scale path to 1.0?
CGAffineTransform transform = CGAffineTransformMakeScale(1.0, 1.0);
CGPathRef transformedPath = CGPathCreateCopyByTransformingPath(path, &transform);
self.drawingLayer.path = transformedPath;
CGPathRelease(path);
CGPathRelease(transformedPath);

How do I prevent path width from enlarging when zooming?


Solution

  • You need to divide the line width with the zoom factor.By default line width is 1.

    So create property for the same and when you apply zoom with gesture divide it.

    i.e zoom = 4.0 then line width = 1.0/4.0

    and same as if zoom is 2 then 1.0/2.0

    Hope it is helpful