如何使用左上角和左上角创建圆形UIButton仅左下角半径

时间:2015-10-04 19:13:24

标签: ios swift uibutton uibezierpath

我需要创建一个左上角和左上角的按钮。左下角半径就像这个enter image description here。我尝试创建以下扩展,该扩展取自stackoverflow的一个答案:

extension UIButton {

   func roundCorners(corners:UIRectCorner, radius: CGFloat) {
       self.layer.borderColor = GenerateShape.UIColorFromHex(0x989898, alpha: (1.0-0.3)).CGColor
       self.layer.borderWidth = 1.0
       let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
       let mask = CAShapeLayer()
       mask.path = path.CGPath
       self.layer.mask = mask

   }
}

然后调用这样的方法:

self.collectionBtn.roundCorners(.TopLeft | .BottomLeft, radius: cornerRadius) 

此代码生成以下形状enter image description here

为什么左上角和左上角呢?左下角看不见?我该怎么办才能让它们可见?

2 个答案:

答案 0 :(得分:7)

您的代码正在为您的按钮应用遮罩层。这会导致您在遮罩层中安装的形状之外的任何内容被遮盖掉。当你安装一个圆角的路径时,它基本上"刮掉"两个角落。那不是你想要的。

您可能想要创建一个形状图层并将其安装为按钮图层的常规子图层,而不是作为遮罩图层。但是,您需要将填充颜色设置为清除。

更改您的代码:

extension UIButton 
{
  func roundCorners(corners:UIRectCorner, radius: CGFloat) 
  {
    let borderLayer = CAShapeLayer()
    borderLayer.frame = self.layer.bounds
    borderLayer.strokeColor = GenerateShape.UIColorFromHex(0x989898, 
      alpha: (1.0-0.3)).CGColor
    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);
  }
}

编辑:

设置角落的语法在Swift 2中不起作用:

self.collectionBtn.roundCorners(.TopLeft | .BottomLeft, radius: 10)

应该是

self.collectionBtn.roundCorners([.TopLeft, .BottomLeft], radius: 10)

答案 1 :(得分:0)

以下是如何做到这一点:

CGRect maskRect = CGRectMake(0.0, 0.0, CGRectGetWidth(<#something here#>), CGRectGetHeight(<#something here#>));
CAShapeLayer *maskLayer = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:maskRect
                                           byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerTopLeft)
                                                 cornerRadii:CGSizeMake(<#corner radius#>, <#corner radius#>)];
maskLayer.path = path.CGPath;
self.layer.mask = maskLayer;