Search code examples
swiftsprite-kitfillcgpathskshapenode

Fill SKShapeNode created from CGPath


I'm trying to create a custom SKShapeNode based on an array of points. The points form a closed shape and the shape ultimately needs to be filled.

This is what I've come up with so far, but for some reason the stroke draws fine but the shape stays empty. What did I miss?

override func didMoveToView(view: SKView)
{
    let center = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
    let path = CGPathCreateMutable()


    CGPathMoveToPoint(path, nil, center.x, center.y)
    CGPathAddLineToPoint(path, nil, center.x + 50, center.y + 50)

    CGPathMoveToPoint(path, nil, center.x + 50, center.y + 50)
    CGPathAddLineToPoint(path, nil, center.x - 50, center.y + 50)

    CGPathMoveToPoint(path, nil, center.x - 50, center.y + 50)
    CGPathAddLineToPoint(path, nil, center.x - 50, center.y - 50)

    CGPathMoveToPoint(path, nil, center.x - 50, center.y - 50)
    CGPathAddLineToPoint(path, nil, center.x, center.y)

    CGPathCloseSubpath(path)

    let shape = SKShapeNode(path: path)
    shape.strokeColor = SKColor.blueColor()
    shape.fillColor = SKColor.redColor()
    self.addChild(shape)
}

Solution

  • Something is wrong with your path. You typically call CGPathMoveToPoint to set the path’s starting point, followed by a series of CGPathAdd* calls to add line segments to the path. Try to create it like this:

    let path = CGPathCreateMutable()         
    CGPathMoveToPoint(path, nil, center.x, center.y)
    CGPathAddLineToPoint(path, nil, center.x + 50, center.y + 50)
    CGPathAddLineToPoint(path, nil, center.x - 50, center.y + 50)
    CGPathAddLineToPoint(path, nil, center.x - 50, center.y - 50)
    CGPathCloseSubpath(path)
    

    Read CGPath Reference (search CGPathMoveToPoint) for more details.