Search code examples
iosswiftdrawinguibezierpathcashapelayer

Swift: addLine ignored in between two addArc calls when creating a path


This code does what I expect. It draws an arc, then adds a line 50 points wide from the top of that arc:

path.move(to: .init(x: myX, y: myY))

path.addArc(withCenter: CGPoint(x: centerX, y: centerY), radius: radius1, startAngle: .pi, endAngle: (3 * .pi)/2, clockwise: true)

let currentPoint = path.currentPoint
path.addLine(to: CGPoint(x: currentPoint.x + 50, y: currentPoint.y))

This code ignores the addLine for adding a 50 points wide line and just starts the second arc right at the top of the first arc.

path.move(to: .init(x: myX, y: myY))

path.addArc(withCenter: CGPoint(x: centerX, y: centerY), radius: radius1, startAngle: .pi, endAngle: (3 * .pi)/2, clockwise: true)

let currentPoint = path.currentPoint
path.addLine(to: CGPoint(x: currentPoint.x + 50, y: currentPoint.y))

path.addArc(withCenter: CGPoint(x: centerX + 50, y: centerY), radius: radius1, startAngle: (3 * .pi)/2, endAngle: .pi, clockwise: false)

With this second bit of code, I get the exact same output if I comment out the addLine code. I get the exact same output if I change the addLine code to add 300 pixels points instead of 50. The addLine code is ignored and I get two arcs, without a line between where the first ends and the second begins.

Any suggestions? Thanks so much!


Solution

  • You said:

    With this second bit of code, I get the exact same output if I comment out the addLine code.

    Yep, when you add an arc to an existing path, it will automatically draw a line from the currentPoint to the start of this second arc. If you don’t want it to add the line in between, you need to do a move(to:) in your path to where the second arc will start if you don’t want the line in-between. Or create two paths, one for each arc, and stroke them separately.

    I get the exact same output if I change the addLine code to add 300 pixels instead of 50.

    That doesn’t quite make sense and I cannot reproduce that behavior. For example, this is what I get when I move the second arc 50pt (and I’ll animate the stroke so you can see what’s going on):

    enter image description here

    But this is what I get when I move the line 300pt (but keep the second arc only 50pt from the first):

    enter image description here

    Clearly, if you not only make the line 300pt long, but move the center of the second arc by 300pt as well, then it will be just like the first example (except further apart).


    However, if I replace your addLine(to:) with move(to:), then you won’t get the line in-between them:

    enter image description here


    FWIW, in all of these examples, I didn’t know what you were using for myX and myY, so I used a point to the left of the first arc. Clearly, if you don’t want that extra line, move myX and myY to the start of the first arc (or just comment that out entirely).