我正在尝试基于点数组创建自定义 SKShapeNode。 这些点形成一个封闭的形状,最终需要填充该形状。
这是我到目前为止所想到的,但由于某种原因,笔画画得很好,但形状仍然是空的。我错过了什么?
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)
}
你的
path
有问题。您通常调用 CGPathMoveToPoint
来设置路径的起点,然后调用一系列 CGPathAdd*
来向路径添加线段。尝试像这样创建它:
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)
阅读 CGPath 参考(搜索
CGPathMoveToPoint
)了解更多详细信息。
例如,您不需要使用 CGPath 来执行此操作,您可以进行如下操作:
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))
...