swift 填充从CGPath创建的SKShapeNode

okxuctiv  于 2023-11-16  发布在  Swift
关注(0)|答案(2)|浏览(100)

我正在尝试创建一个基于点数组的自定义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)
}

字符串

1dkrff03

1dkrff031#

您的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 Reference(搜索CGPathMoveToPoint)了解更多详情。

bihw5rsg

bihw5rsg2#

例如,你不需要使用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))
...

字符串

相关问题