在GameScene上画一条简单的线



我试图从我开始点击并按住的点到我移动手指的点绘制简单的线条。所以它总是一条简单的线,有起点和终点。我尝试了不同的教程,但它什么也没画,也没有收到任何错误。

这是我在GameScene中的代码.swift

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
   /* Called when a touch begins */
    if let touch = touches.first {
        self.tapDown = true
        self.firstPoint = touch.locationInView(self.view)
    }
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    self.tapDown = false
    self.firstPoint = CGPoint.zero
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first where self.tapDown {
        let currentPoint = touch.locationInView(self.view)
        let context = UIGraphicsGetCurrentContext()
        CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor)
        let lines = [CGPointMake(self.firstPoint.x,self.firstPoint.y),CGPointMake(currentPoint.x,currentPoint.y)]
        CGContextAddLines(context,lines,4)
        CGContextStrokePath(context)
    }
}

在ViewController中.swift在viewDidLoad之后,我把这个:

UIGraphicsBeginImageContext(skView.frame.size)

这是怎么回事?

UIGraphicsGetCurrentContext()返回当前的 CoreGraphics 绘图上下文。在两种情况下,只有当前图形上下文:

  • 如果你在 UIView drawRect: 方法(或从一个方法调用的代码,或类似的函数,例如用于 CALayer 的函数)
  • 如果您已经启动了自己的CG上下文并通过调用UIGraphicsPushContext使其"当前"。

touchesMoved方法中,这两种情况都不是这样,因此调用返回nil,后续绘图代码失败。(如果它默默地失败,我会感到惊讶...不是至少有一些关于使用零上下文绘制的控制台消息吗?

此外,SpriteKit不使用CoreGraphics进行绘制 - 它使用OpenGL或Metal在GPU上渲染,因此您无需在SpriteKit中发出绘图命令,而是描述SpriteKit应该绘制的场景。有关使用 SKShapeNode 向 SpriteKit 场景添加线条的示例,请参阅此答案。

好的,我让它工作了,我现在使用 SKShapeNode,但原因是我使用的是 touch.locationInView 而不是 touch.locationInNode,它为我的触摸点提供了其他坐标。

locationInView和locationInNode有什么区别???

工作代码:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        self.tapDown = true
        self.firstPoint = touch.locationInNode(self)
    }
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    self.tapDown = false
    self.firstPoint = CGPoint.zero
    self.enumerateChildNodesWithName("line", usingBlock: {node, stop in
        node.removeFromParent()
    })
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    self.enumerateChildNodesWithName("line", usingBlock: {node, stop in
        node.removeFromParent()
    })
    if let touch = touches.first where self.tapDown {
        let currentPoint = touch.locationInNode(self)
        let path = CGPathCreateMutable()
        CGPathMoveToPoint(path, nil, self.firstPoint.x, self.firstPoint.y)
        CGPathAddLineToPoint(path, nil, currentPoint.x, currentPoint.y)

        let shapeNode = SKShapeNode()
        shapeNode.path = path
        shapeNode.name = "line"
        shapeNode.glowWidth = 2.5
        shapeNode.strokeColor = UIColor.blueColor()
        shapeNode.lineWidth = 2
        shapeNode.zPosition = 1
        self.addChild(shapeNode)
    }
}

最新更新