我正在尝试从我开始点击并按住的点到我将手指移动到的点绘制一条简单的线。所以它总是一条简单的线,有起点和终点。我尝试了不同的教程,但它什么也没画,我也没有收到任何错误。
这是我在 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)
这里有什么问题吗?
最佳答案
UIGraphicsGetCurrentContext()
返回当前的 CoreGraphics 绘图上下文。在两种情况下只有当前绘图上下文:
- 如果您在
UIView drawRect:
方法中(或从一个或类似函数调用的代码,例如CALayer
s 的函数) - 如果您已经启动了自己的 CG 上下文并通过调用
UIGraphicsPushContext
将其设置为“当前”。
在您的 touchesMoved
方法中,这两种情况都不是,因此调用返回 nil
并且后续绘图代码失败。 (如果它无声地失败,我会感到惊讶......难道至少没有一些关于使用 nil 上下文绘制的控制台消息吗?)
此外,SpriteKit 不使用 CoreGraphics 进行绘制 — 它使用 OpenGL 或 Metal 在 GPU 上进行渲染,因此您不必在 SpriteKit 中发出绘图命令,而只需描述 SpriteKit 应该绘制的场景。参见 this answer有关使用 SKShapeNode
向 SpriteKit 场景添加线条的示例。
关于ios - 在 GameScene 上画一条简单的线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34797078/