2017-04-22 65 views
1

我有一个SKShapeNode,如果满足一个特定的条件,它需要将它的每一个角落圆角。阅读下面链接提供的答案,这看起来很简单,因为我只是使用| =来舍入需要四舍五入的添加角(4x if语句)。Round Specific Corners - SKShapeNode

How to write a generic UIRectCorner function?

但是,这是行不通的!当我使用下面的代码,我得到错误信息“Binart运营商‘| =’不能被应用到两个‘UIRectCorner’操作数”

var corners: UIRectCorner = UIRectCorner(rawValue: 0) | UIRectCorner(rawValue: 1) 

var corners: UIRectCorner = UIRectCorner(rawValue: 0) 
corners |= UIRectCorner(rawValue: 1) 

我必须做一些错误,但我无法弄清楚什么?任何帮助将非常感激。

回答

1

我写了一个非常方便的扩展,我在所有的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 
    } 
} 
+0

对不起,回复迟了。这看起来很棒!但是我在'if topLeft'这一行发现一个错误,'容器字面量中的预期表达式'。你知道我为什么会得到这个错误吗? – Jarron

+0

对不起,之前有一个错字。它应该以'UIRectCorner()'而不是'UIRectCorner'结尾(['。我修复了它 – TheValyreanGroup

+0

请考虑投票或标记作为答案,如果你觉得这有助于或解决你的问题。很高兴我可以帮忙。 – TheValyreanGroup

1

排序解决了我的问题。 | =和+ =不起作用,但= [previousValue,newValue]似乎工作。我的代码如下。如果有更好的方法,请告诉我。

func roundCorners() { 

    let TR = true 
    let TL = true 
    let BR = false 
    let BL = true 

    var corners: UIRectCorner = [] 

    if TR == true { 
     corners = [corners, .topRight] 
    } 

    if TL == true { 
     corners = [corners, .topLeft] 
    } 

    if BR == true { 
     corners = [corners, .bottomRight] 
    } 

    if BL == true { 
     corners = [corners, .bottomLeft] 
    } 

    let rect = CGRect(x: -50, y: -50, width: 100, height: 100) 
    let cornerSize = CGSize(width: 10, height: 10) 

    let shape = SKShapeNode() 
    shape.fillColor = UIColor.black 
    shape.path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: cornerSize).cgPath 
    addChild(shape) 

}