5

我找到了这个解决方案,但我不能把它变成 swift 代码

这是我尝试的

var pattern[2]:CGFloat; this 

var dashed: CGPathRef = CGPathCreateCopyByDashingPath(CGPathCreateCopyByDashingPath(path, transform, phase, lengths, count);

var myShapeNode: SKShapeNode!;

        var CGPathCreateCopyByDashingPath:CGPathRef;
4

5 回答 5

12

这就是您如何快速绘制虚线的方法。您可以根据需要更改参数。

let bezierPath = UIBezierPath()
let startPoint = CGPointMake(0, 250)
let endPoint = CGPointMake(450, 250)
bezierPath.moveToPoint(startPoint)
bezierPath.addLineToPoint(endPoint)

var pattern : [CGFloat] = [10.0, 10.0]
let dashed = CGPathCreateCopyByDashingPath (bezierPath.CGPath, nil, 0, pattern, 2)

var shapeNode = SKShapeNode(path: dashed)
shapeNode.position = CGPointMake(100, 100)
self.addChild(shapeNode)
于 2015-01-21T17:24:16.103 回答
5

在 Swift 4 中:

    let square = SKShapeNode(rectOf: CGSize(width: 64, height: 64))
    let pattern : [CGFloat] = [4.0, 4.0]

    let dashed = square.path?.copy(dashingWithPhase: 1, lengths: pattern)

    let shapeNode = SKShapeNode(path: dashed!)
    shapeNode.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
    shapeNode.fillColor = SKColor.clear
    shapeNode.strokeColor = SKColor.red
    shapeNode.lineWidth = 2
    self.addChild(shapeNode)
于 2018-12-20T12:15:17.630 回答
2

斯威夫特 5

if let path = path?.copy(dashingWithPhase: 1, lengths: [5, 5]) {
    let line = SKShapeNode(path: path)
    line.strokeColor = .white
    self.addChild(line)
}

在此处输入图像描述

于 2020-01-27T12:09:27.283 回答
2

对于任何想弄清楚如何像我一样将相同的主体应用于 SKShapeNode 的人,这里有一个示例。带有蓝色虚线的矩形。

import SpriteKit
import GameplayKit

let square = SKShapeNode(rectOfSize: CGSize(width: 64, height: 64))
let circle = SKShapeNode(circleOfRadius: 20.0)

var pattern : [CGFloat] = [2.0, 2.0]
let dashed = CGPathCreateCopyByDashingPath (square.path, nil, 0, pattern, 2)

var shapeNode = SKShapeNode(path: dashed!)
shapeNode.fillColor = UIColor.blueColor()
shapeNode.strokeColor = UIColor.blueColor()

带虚线的正方形

于 2016-08-17T11:33:21.473 回答
1

添加到上面 Mike Glukhov 提供的解决方案中,这是我的解决方案:

func drawTrace(pointArray: Array<CGPoint>) {
    if pointArray.count > 1 {
        let pattern : [CGFloat] = [10.0, 10.0]

        let path = CGMutablePath.init()

        // start at the first point.
        path.move(to: pointArray[0])

        // now add all of the others.
        for p in 1 ..< pointArray.count {
            path.addLine(to: pointArray[p])
        }

        // create the dashed path.
        let dashedPath = path.copy(dashingWithPhase: 1, lengths: pattern)

        let dashName = "dash"

        // now create the node
        let line = SKShapeNode(path: dashedPath)
        line.strokeColor = .white
        line.name = dashName

        if let parent = self.parent {
            if let oldLine = parent.childNode(withName: dashName) {
                oldLine.removeFromParent()
            }

            parent.addChild(line)
        }
    }
}
于 2020-05-04T10:51:21.587 回答