Search code examples
iosswiftxcodeuibezierpathcashapelayer

With strokeColor, a line is drawn from the center to the circumference




I am using swift 4.
I wrote the code below and tried to draw a circle with stroke.
However, with the code below I could not draw my desired circle.
The problem is that the line is drawn from the center of the circle to the outer periphery
(strictly speaking, toward the coordinate point of the 'startAngle' property).

I want to erase the line, what should I do?

(I prepared an image.)

class Something{

    var line:[CAShapeLayer] = []
    var path:[UIBezierPath] = []

    func drawingNow(){
            let layer = CAShapeLayer()
            self.layer.addSublayer(layer)
            self.line.append(layer)

            let addPath: UIBezierPath = UIBezierPath()
            addPath.move(to: CGPoint(x: 100, y: 100))
            addPath.addArc(
                withCenter: CGPoint(x: 100, y: 100),
                radius: CGFloat(50),
                startAngle: CGFloat(//someangle),
                endAngle: CGFloat(//someangle),
                clockwise: true
            )

            self.path.append(addPath)

            //self.line.last!.strokeColor = etc... (If don't use "override func draw()")
            self.line.last!.fillColor = UIColor.clear.cgColor
            self.line.last!.path = addPath.cgPath

            self.setNeedsDisplay()
    }

    override func draw(_ rect: CGRect) {
        if self.path.count != 0{
            UIColor.orange.setStroke()
            self.path.last!.stroke()
        }
    }
}

Image


Solution

  • After calling addPath.move(to: CGPoint(x: 100, y: 100)), the UIBezierPath moved to the specified coordinate. Now you are telling it to add an arc from there with a centre of (100, 100). To draw an arc with a centre (100, 100), it first need to move to the circumference. But at this point it already starts drawing! That's just how addArc works. The same goes for addLine. Look at the docs:

    This method adds the specified arc beginning at the current point.

    So the arc always starts at the current point, which is (100, 100).

    Instead of telling it to move to the centre first, just tell it to draw an arc by removing the move(to:)` line.