Search code examples
iosswiftsprite-kitcgpathskshapenode

How to change the fill rule of SKShapeNode when filling color


I'm using SKShapeNode to create a view element which is used in my game, it should be like the following picture, with only 2 visible curves and fill color inside.

enter image description here

Here is my code:

    override func sceneDidLoad() {

        let shapeNode = SKShapeNode()
        shapeNode.fillColor = .red
        shapeNode.strokeColor = .white
        shapeNode.lineWidth = 5

        let path = CGMutablePath()
        let radius:CGFloat = 250
        path.addArc(center: CGPoint(x:0, y:300), radius: radius, startAngle: CGFloat.pi*7/6, endAngle: CGFloat.pi*11/6, clockwise: false)
        path.addArc(center: CGPoint(x:0, y:-300), radius: radius, startAngle: CGFloat.pi*1/6, endAngle: CGFloat.pi*5/6, clockwise: false)

        shapeNode.path = path

        self.addChild(shapeNode)
    }

But I got an extra straight line on right side which is not I want.

enter image description here

So I tried to move to another arc directly

        path.addArc(center: CGPoint(x:0, y:300), radius: radius, startAngle: CGFloat.pi*7/6, endAngle: CGFloat.pi*11/6, clockwise: false)
        path.move(to: CGPoint(x:cos(CGFloat.pi/6)*radius, y: -300+sin(CGFloat.pi/6)*radius))
        path.addArc(center: CGPoint(x:0, y:-300), radius: radius, startAngle: CGFloat.pi*1/6, endAngle: CGFloat.pi*5/6, clockwise: false)

I got something like this, which is not I want either.

enter image description here

I've learned that I can change the fill rule of CAShapeLayer by using CGPathFillRule after checking Apple documents, but I have no idea how to connect SKShapeNode and CGPathFillRule.

Any idea about this?


Solution

  • I don't think the fill rule is going to fix things here. You need a way to separate the portions of the border that you want stroked. Simplest is probably to create two shape nodes, one done as in your first case and filled, and a second done as the second case and stroked.