ios - 使用SKShapeNode绘制和删除线条

时间:2017-09-08 03:22:12

标签: ios swift sprite-kit

我想通过拖动手指绘制一条线,现在我可以从第一个点击位置到当前位置绘制线条。但我无法删除之前绘制的线条。我使用此代码删除行。

for line in self.children {
    line.removeFromParent()
}

但添加新行时会显示所有已删除的行。

下面是我的代码。

import SpriteKit
import GameplayKit

class GameScene: SKScene {

    private var label : SKLabelNode?
    private var spinnyNode : SKShapeNode?

    // For Line
    var startPoint: CGPoint?
    var path = CGMutablePath()

    override func didMove(to view: SKView) {
    }


    func touchDown(atPoint pos : CGPoint) {
        print("touchDown")
        startPoint = pos
    }

    func touchMoved(toPoint pos : CGPoint) {
        print("touchMoved")

        for line in self.children {
            line.removeFromParent()
        }

        plotLine(atPoint: startPoint!, toPoint: pos)
    }

    func plotLine(atPoint start: CGPoint, toPoint end: CGPoint) {
        path.move(to: start)
        path.addLine(to: end)

        let temp_shape = SKShapeNode()
        temp_shape.path = path
        temp_shape.strokeColor = UIColor.white
        temp_shape.lineWidth = 2

        self.addChild(temp_shape)
    }

1 个答案:

答案 0 :(得分:1)

以这种方式尝试:

var startPoint: CGPoint?
var tempLine: SKShapeNode!
var completedLines: [SKShapeNode] = []

func touchDown(atPoint pos : CGPoint) {
    print("touchDown")
    startPoint = pos

    tempLine = SKShapeNode()
    tempLine.strokeColor = UIColor.white
    tempLine.lineWidth = 2
    self.addChild(tempLine)
}

func touchMoved(toPoint pos : CGPoint) {
    print("touchMoved")

    plotLine(atPoint: startPoint!, toPoint: pos)
}

func touchUp(atPoint pos: CGPoint) {
    completedLines.append(tempLine)
    tempLine = nil
}

func plotLine(atPoint start: CGPoint, toPoint end: CGPoint) {
    var path = CGMutablePath()
    path.move(to: start)
    path.addLine(to: end)

    tempLine.path = path
}

func deleteLine(atIndex index: Int) {
    completedLines[index].removeFromParent()
    completedLines.remove(at: index)
}

func deleteLastLine() {
    if let lastLine = completedLines.last {
        lastLine.removeFromParent()
        completedLines.dropLast()
    }
}

因此,每个tempLine现在都将保存在数组中。您可以调用删除功能,在哪里需要删除行。例如,如果您需要在开始新行之前删除上一行,则需要在touchDown中执行此操作,如下所示:

func touchDown(atPoint pos : CGPoint) {
    self.deleteLastLine()

    print("touchDown")
    startPoint = pos

    tempLine = SKShapeNode()
    tempLine.strokeColor = UIColor.white
    tempLine.lineWidth = 2
    self.addChild(tempLine)
}