Gerome Pistre
Gerome Pistre

Reputation: 467

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)
}

Upvotes: 1

Views: 987

Answers (2)

WangYudong
WangYudong

Reputation: 4423

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.

Upvotes: 1

Alexey Pichukov
Alexey Pichukov

Reputation: 3405

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))
...

Upvotes: 0

Related Questions