ios - 在 GameScene 上画一条简单的线

标签 ios swift sprite-kit

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

这是我在 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: 方法中(或从一个或类似函数调用的代码,例如 CALayers 的函数)
  • 如果您已经启动了自己的 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/

相关文章:

swift - 解码保存后 iOS SpriteKit 碰撞检测失败

ios - 是否可以仅针对 iphone5 和 6 发布使用 spritekit 和 swift 开发的游戏

ios - SWIFT 4.1 无法使用类型为 'Double' 的参数列表调用类型为 '(String?)' 的初始值设定项

ios - 图表 : Get selected bar data only when tapped inside the bar

iphone - unity生成iphone源码后无法运行游戏

ios - 在 iOS 7 下,如何动态隐藏和显示状态栏(无论何时)

xcode - 使用 Swift 解析 : this class is not key value coding-compliant for the key submit. '

ios - Swift 4 : Checking if week, 月、2 个月等自使用日历首次启动以来已过去

ios - swift : Redundant conformance of Viewcontroller to protocol UIGestureRecognizerDelegate

xcode - 如何继续调用函数直到它返回与以前不同的输出?