【问题标题】:How to get rounded corners only for topLeft and bottomLeft corners?如何仅为左上角和左下角获得圆角?
【发布时间】:2017-02-07 07:40:48
【问题描述】:

我已经关注了其他 stackoverflow 线程并创建了 CAShapeLayer 并将其添加到按钮层。

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

但问题是我得到了颜色清晰的角落,但我希望它们是绿色的。检查下图中带有“Mon”和“Fri”的按钮,以便清楚地了解问题。

【问题讨论】:

标签: ios swift


【解决方案1】:

在您的代码中,您忘记将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)

输出

【讨论】:

  • 我没有投反对票。我只是放弃了投票。添加形状层作为子层实际上有帮助。谢谢
  • 查看您的答案版本,第一个版本是错误的。也许那个版本被投票了?
【解决方案2】:

尝试使用以下函数:

 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);
  }

【讨论】:

  • 解决方案 1 我已经尝试过但失败了。但解决方案 2 有效。这个棒极了。谢谢
猜你喜欢
  • 1970-01-01
  • 2017-11-12
  • 1970-01-01
  • 2014-10-26
  • 2015-09-22
  • 1970-01-01
  • 2017-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多