我试图从我开始点击的位置绘制简单的线条并保持到我移动手指的位置。所以它总是一个简单的起点和终点。我尝试了不同的教程,但没有任何内容,我没有任何错误。
这是我在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)
}
}
在viewDidLoad之后的ViewController.swift中我把它放在:
UIGraphicsBeginImageContext(skView.frame.size)
这里有什么问题?
答案 0 :(得分:1)
UIView drawRect:
返回当前的CoreGraphics绘图上下文。在两种情况下只有当前的绘图上下文:
CALayer
方法中(或从一个或类似函数调用的代码,例如UIGraphicsPushContext
的方法)touchesMoved
使其成为“最新”。 nil
方法中的情况都不是这样,因此调用返回SKShapeNode
,后续绘图代码失败。 (如果它失败了,我会感到惊讶......至少有一些关于使用nil上下文绘制的控制台消息吗?)
此外,SpriteKit不使用CoreGraphics进行绘制 - 它使用OpenGL或Metal在GPU上渲染,因此您不要在SpriteKit中发出绘图命令,只要描述SpriteKit应该绘制的场景。有关使用git lfs install
向SpriteKit场景添加一行的示例,请参阅this answer。
答案 1 :(得分:0)
好的我工作了,我现在使用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)
}
}