Make independent copy of UIBezierPath?
Asked Answered
C

3

9

I have a complex UIBezierCurve which I need to draw once with some particular line parameters, and then draw it again as overlay with other line parameters, but also I need the last part of the curve to be slightly shorter than in previous one.

To do this I want to create the curve by addLineToPoint:, moveToPoint: up to the last part, then make a copy of this curve and add the final segments of the line differently in original and copied curves. And then I stroke the original curve, and the copied one.

The problem is that it doesn't work as I expected. I create a copy of the curve by:

UIBezierPath* copyCurve = [originalCurve copy];

And the drawing which I do in the originalCurve after that, is applied also to the copyCurve, so I can't do independent drawing for any of this curves.

What is the reason for this connection between original and copy and how can I get rid of it?

EDIT 1: A solution which I've found is to create the copy in the following way:

UIBezierPath* copyCurve=[UIBezierPath bezierPathWithCGPath:CGPathCreateMutableCopy(originalCurve.CGPath)];

Since this works properly, maybe the problem is in the immutability of the copy I get with

[originalCurve copy]
Coan answered 13/7, 2012 at 14:10 Comment(2)
Did you alloc/init your copyCurve?Kwarteng
No, just what is written in my question...Coan
C
25

Create a new, identical path by using the CGPath.

path2 = [UIBezierPath bezierPathWithCGPath:path1.CGPath];

The CGPath property docs state that:

This property contains a snapshot of the path at any given point in time. Getting this property returns an immutable path object that you can pass to Core Graphics functions.

Cuticula answered 13/7, 2012 at 14:37 Comment(2)
Please, take a look at my edit of the question. It seems to me that I will not be able to change the immutable path object, so probably I need the mutable one.Coan
You can't change the CGPath, but the UIBezierPath object made with the CGPath is mutable.Cuticula
T
4

copy() works fine for me as of Swift 4.

let copiedPath = originalPath.copy() as! UIBezierPath
copiedPath.addLine(...)

The originalPath does not get modified.

Tildie answered 15/2, 2019 at 23:13 Comment(0)
C
2

In addition to @jrturton answer :-

Alternatively we can use :-

 let  path = UIBezierPath(ovalIn: pathRect)
 let newPath = path.cgPath.copy(strokingWithWidth: strokeWidth, lineCap: .butt, lineJoin: .miter, miterLimit: 0)

enter image description here

Reference

Copulation answered 12/12, 2016 at 10:53 Comment(1)
update it for swift 3 let storkedArc = arc.copy(strokingWithWidth: 5.0, lineCap: .butt, lineJoin: .miter, miterLimit: 10)Binky

© 2022 - 2024 — McMap. All rights reserved.