2017-02-07 53 views
0

我跟着其他stackoverflow線程並創建CAShapeLayer並將其添加到按鈕層。如何只爲topLeft和bottomLeft角獲得圓角?

let bazierPath = UIBezierPath.init(roundedRect: button.bounds, byRoundingCorners: [UIRectCorner.bottomLeft, UIRectCorner.topLeft], cornerRadii: CGSize(width: 10.0, height: 10.0)) 
      let shapeLayer = CAShapeLayer() 
      shapeLayer.frame = button.bounds 
      shapeLayer.path = bazierPath.cgPath 
      shapeLayer.strokeColor = UIColor.green.cgColor 
      shapeLayer.lineWidth = 1.0 
      button.layer.mask = shapeLayer 

但問題是我越來越清晰的顏色的角落,但我希望他們是綠色的。檢查以下圖像中帶有「星期一」和「星期五」的按鈕,以清楚瞭解問題。

enter image description here

+0

檢查:http://stackoverflow.com/questions/37163850/round-top-corners-of-a-uibutton-in-swift – Khuong

回答

1

嘗試使用下面的函數:

fun createRoundCorners(corners:UIRectCorner, radius: CGFloat) 
    { 
    let borderLayer = CAShapeLayer() 
    borderLayer.frame = self.layer.bounds 
    borderLayer.strokeColor = // Add your color 
    borderLayer.fillColor = UIColor.clearColor().CGColor 
    borderLayer.lineWidth = 1.0 
    let path = UIBezierPath(roundedRect: self.bounds, 
     byRoundingCorners: corners, 
     cornerRadii: CGSize(width: radius, height: radius)) 
    borderLayer.path = path.CGPath 
    self.layer.addSublayer(borderLayer); 
    } 
+0

解決方案1我已經嘗試失敗。但解決方案2正在工作。這個棒極了。謝謝 –

+0

確定讓我刪除1。 – User511

2
在你的代碼

你忘記了addSublayer添加到主層contentView.layer.addSublayer(subLayer)樣品目的

let contentView = UIView(frame: CGRect(x: CGFloat(50), y: CGFloat(100), width: CGFloat(200), height: CGFloat(100))) 
    self.view.addSubview(contentView) 
    let subLayer = CAShapeLayer() 
    subLayer.fillColor = UIColor.blue.cgColor 
    subLayer.strokeColor = UIColor.green.cgColor 
    subLayer.lineWidth = 1.0 
    subLayer.path = UIBezierPath(roundedRect: contentView.bounds, byRoundingCorners: [UIRectCorner.bottomLeft, UIRectCorner.topLeft], cornerRadii: CGSize(width: 10.0, height: 10.0)).cgPath 
    contentView.layer.addSublayer(subLayer) 

輸出

enter image description here

+0

可我知道downvote原因 –

+0

我沒有downvoted它。我剛剛放棄了。添加形狀層作爲子層實際上有幫助。謝謝 –

+0

看着你答案的版本,第一個版本是錯誤的。也許那個版本被投票了? – vikingosegundo