设置SKShapeNode的一个角的半径

时间:2018-12-07 09:59:46

标签: ios swift sprite-kit

我想更改SKShapeNode(矩形)的两个角的半径,但找不到有效的解决方案。 我尝试使用路径,但没有用。 Swift 4.2,iOS 12.1.1,Xcode 10.1

let shape = SKShapeNode()
shape.path = UIBezierPath(roundedRect: CGRect(x: -128, y: -128, width: 256, height: 256), cornerRadius: 64).cgPath
shape.position = CGPoint(x: frame.midX, y: frame.midY)
shape.fillColor = UIColor.red
shape.strokeColor = UIColor.blue
shape.lineWidth = 10
addChild(shape)

1 个答案:

答案 0 :(得分:2)

我做了一个函数,可以让您自定义每个拐角半径为任意大小。您可以有一个半径为1,2,3或4个角。如果您始终只希望有两个角,那么我建议您创建一个包装函数,这样每次调用时都不必填写太多参数。

func CustomRoundRectPath(_ rect:CGRect, _ TLR:CGFloat,_ TRR:CGFloat,_ BLR:CGFloat,_ BRR:CGFloat) -> CGPath {

    let w = rect.width
    let h = rect.height

    //TLP:(TLP)
    let TLP = CGPoint(x: TLR, y: h - TLR)
    let TRP = CGPoint(x: w - TRR, y: h - TRR)
    let BLP = CGPoint(x: BLR, y: BLR)
    let BRP = CGPoint(x: w - BRR, y: BRR)

    //Create path and addComponents
    let path = CGMutablePath()
    path.addArc(center: TLP, radius: TLR, startAngle: CGFloat.pi, endAngle: CGFloat.pi/2, clockwise: true)
    path.addLine(to: CGPoint(x: TRP.x, y: h))
    path.addArc(center: TRP, radius: TRR, startAngle: CGFloat.pi/2, endAngle: 0, clockwise: true)
    path.addLine(to: CGPoint(x: w, y: BRP.y))
    path.addArc(center: BRP, radius: BRR, startAngle: 0, endAngle: -CGFloat.pi/2, clockwise: true)
    path.addLine(to: CGPoint(x: BLP.x, y: 0))
    path.addArc(center: BLP, radius: BLR, startAngle: -CGFloat.pi/2, endAngle: -CGFloat.pi, clockwise: true)
    path.addLine(to: CGPoint(x: 0, y: TLP.y))

    return path
}