Search code examples
core-graphics

context.Path returning nil


I have the following code that draws into a CALayer subclass' context.

override func draw(in con: CGContext) {

    //  super.draw(in: con) //with/out makes no diff

      let endAng = CGFloat(Float.pi * 2) 

      con.addArc(center: position,
                 radius: 30,
                 startAngle: 0,
                 endAngle: endAng,
                 clockwise: false)
      con.setStrokeColor(UIColor.red.cgColor)
      con.setLineWidth(CGFloat(thickness / 5))
      con.strokePath()


      self.path = con.path

In that last line, I'm trying to save the path to do more drawing with it when a user goes into another mode. But after the assignement self.path == nil

The docs simply say:

Returns a path object built from the current path information in a graphics context.

Why, if I just had been adding path components to my CALayer subclass' context is the path getter returning a nil path? The documentation here does not help me debug.

So, all the drawing functions like addArc say they add these shapes to the current path (and i indeed see them rendered in my layer), yet on the next line when I query for the current context's path, it is nil?


Solution

  • The documentation for the strokePath function says:

    The current path is cleared as a side effect of calling this function.

    Move your call to con.path earlier, before you stroke the path.