【问题标题】:SpriteKit and programmatically draw simple graphicsSpriteKit 并以编程方式绘制简单图形
【发布时间】:2016-02-02 05:26:00
【问题描述】:

关于使用 SpriteKit 渲染引擎的任何建议,但有能力以编程方式绘制游戏图形。这些图形很简单,但比矩形和椭圆形略复杂。

我最近发现SKShapeNode 在使用自定义路径时对复杂性有一个上限。我基本上有一个函数可以用一个数字生成随机的CGPath 形状,数字越大,形状越复杂和细节。当我使用较小的数字时,没有问题,但是当我使用较大的数字生成更复杂的路径时,SKShapeNode 给我这个错误。 (我也在iOS9.2.1的真机上测试过)

断言失败:(length + offset

Related Question

现在我不认为使用SKShapeNode 是一个好主意,所以任何关于以编程方式绘制能够很好地与 SpriteKit 配合使用的图形的建议?

我在其他地方读到使用任何可用的图形 API 进行绘制,只要它可以转换为 SKTexture 可以初始化的格式,是正确的方法吗?

【问题讨论】:

    标签: swift sprite-kit swift2


    【解决方案1】:

    如果您将使用SKTexture,您可以使用CGContext 绘制图表。

    首先,您需要创建图表点数组,例如:

    let pathPoints: [CGPoint] = [...] 
    

    然后您需要调用UIGraphicsBeginImageContext(rect.size),其中rect.sizeCGSize 对象,它决定了将在其中嵌入图表的区域的大小,rectCGRect 对象。下一步是创建CGContextRef 及其设置:

    UIGraphicsBeginImageContext(size)
    let context: CGContextRef = UIGraphicsGetCurrentContext()!
    CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor);
    CGContextSetLineWidth(context, lineWidth)
    

    其中lineWidthCGFloat 类型值。

    在此之后,您可以在这样的上下文中创建图表:

    if pathPoints.count > 1 {
        CGContextMoveToPoint(context, pathPoints.first!.x, pathPoints.first!.y)
        for var i = 1; i < pathPoints.count; ++i {
            CGContextAddLineToPoint(context, pathPoints[i].x, pathPoints[i].y)
        }
    }
    CGContextStrokePath(context)
    

    然后你需要像这样创建图像表单上下文:

    let image = UIGraphicsGetImageFromCurrentImageContext()
    

    然后创建纹理形式image 并将其用于将添加到场景中的SKSpriteNode 对象:

    let pathTexture = SKTexture(image: image)
    let pathNode = SKSpriteNode(texture: pathTexture)
    pathNode.position = CGPointMake(rect.origin.x + rect.width/2 - lineWidth/2, rect.origin.y + rect.height/2 - lineWidth/2)
    pathNode.zPosition = 0
    
    someParrentNodeThatOnScene.addChild(pathNode)
    UIGraphicsEndImageContext()
    

    这就是创建图表所需的全部内容。

    【讨论】:

      猜你喜欢
      • 2011-06-30
      • 2012-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-16
      相关资源
      最近更新 更多