我写了一个非常方便的扩展,我在所有的SpriteKit游戏中大量使用。它采用现有的SKShapeNode并复制其所有相关属性,然后删除并制作一个新的角色,并指定要四舍五入的角。注意:如果形状节点有任何子节点,则不应该使用此节点,因为它们不会通过新创建持续存在。因此,在添加任何子项之前,请始终使用此方法。
shapeNode.roundCorners(topLeft:true,topRight: true,bottomLeft:false,bottomRight:false,radius:20,parent:self)
extension SKShapeNode {
func roundCorners(topLeft:Bool,topRight:Bool,bottomLeft:Bool,bottomRight:Bool,radius: CGFloat,parent: SKNode){
let newNode = SKShapeNode(rect: self.frame)
newNode.fillColor = self.fillColor
newNode.lineWidth = self.lineWidth
newNode.position = self.position
newNode.name = self.name
newNode.fillColor = self.fillColor
newNode.strokeColor = self.strokeColor
newNode.fillTexture = self.fillTexture
self.removeFromParent()
parent.addChild(newNode)
var corners = UIRectCorner()
if topLeft { corners = corners.union(.bottomLeft) }
if topRight { corners = corners.union(.bottomRight) }
if bottomLeft { corners = corners.union(.topLeft) }
if bottomRight { corners = corners.union(.topRight) }
newNode.path = UIBezierPath(roundedRect: CGRect(x: -(newNode.frame.width/2),y:-(newNode.frame.height/2),width: newNode.frame.width, height: newNode.frame.height),byRoundingCorners: corners, cornerRadii: CGSize(width:radius,height:radius)).cgPath
}
}
对不起,回复迟了。这看起来很棒!但是我在'if topLeft'这一行发现一个错误,'容器字面量中的预期表达式'。你知道我为什么会得到这个错误吗? – Jarron
对不起,之前有一个错字。它应该以'UIRectCorner()'而不是'UIRectCorner'结尾(['。我修复了它 – TheValyreanGroup
请考虑投票或标记作为答案,如果你觉得这有助于或解决你的问题。很高兴我可以帮忙。 – TheValyreanGroup