Fill an unclosed bezier path in Swift

621 Views Asked by At

I'm trying to create an image similar to the one on the left. I have a NSBezier path (not a closed path) but when I fill it, It seems to only produce the image on the right. I want to fill the path but only the looped part. Any suggestions?

The loops on the left is what I am trying to create

 UIGraphicsBeginImageContext(board.size)
            if let context = UIGraphicsGetCurrentContext() {
                if let path = snake.path {
                    context.setShouldAntialias(false)
                    let transformedPath = CGMutablePath()
                    transformedPath.addPath(path, transform: transform)
                    context.addPath(transformedPath)
                    context.setLineJoin(.round)
                    context.setLineCap(.round)
                    context.setLineWidth(snake.thickness)
                    context.setStrokeColor(UIColor.magenta.cgColor)
                    context.strokePath()
                    context.fillPath()

                }

                if let newImage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage {
                    board.texture = SKTexture(cgImage: newImage)
                }
            }

            UIGraphicsEndImageContext()
1

There are 1 best solutions below

1
rob mayoff On BEST ANSWER

You didn't read the strokePath documentation, which says:

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

So by the time you call fillPath, the current path is empty. There's nothing to fill. You need to set the path again with another call to context.addPath(transformedPath) before calling fillPath.

If you want to fill first and then stroke, you call use context.drawPath(using: .fillStroke) instead. This method fills, then strokes the current path (and then clears the current path).

Also, you didn't set the context's fill color. The default fill color is black, which might not be the color you want.