【问题标题】:Fill SKShapeNode created from CGPath填充从 CGPath 创建的 SKShapeNode
【发布时间】:2015-10-23 10:30:06
【问题描述】:

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

【问题讨论】:

    标签: swift sprite-kit fill cgpath skshapenode


    【解决方案1】:

    您的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)了解更多详情。

    【讨论】:

      【解决方案2】:

      例如你不需要为这个动作使用 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))
      ...
      

      【讨论】:

        猜你喜欢
        • 2019-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-26
        相关资源
        最近更新 更多