2017-04-22 67 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) 

}