0

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)
}
Gerome Pistre
  • 457
  • 6
  • 15

2 Answers2

1

Something wrong with your path. You typically calls 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.

WangYudong
  • 4,335
  • 4
  • 32
  • 54
0

For example you do not need use CGPath for this action, you can make somthing like this:

let points: [CGPoint] = [CGPointMake(center.x, center.y), ...] // All your points
var context: CGContextRef = UIGraphicsGetCurrentContext()

CGContextAddLines(context, points, UInt(points.count))
CGContextSetFillColorWithColor(context, UIColor.redColor().CGColor)
CGContextFillPath(context)

let shape = SKShapeNode(path: CGContextCopyPath(context))
...
Alexey Pichukov
  • 3,377
  • 2
  • 19
  • 22