根据视图设置按钮一侧的拐角半径?

时间:2018-12-13 09:10:11

标签: ios swift uibutton uikit

我必须根据在后台找到的UIView设置拐角半径。我已附上我的开发图片,以供您参考。

this is what I got after developement

3 个答案:

答案 0 :(得分:0)

只需创建如下所示的自定义视图,并将蒙版和路径应用于主层

@IBDesignable class VariableSeparateCornerView: UIView {

    private var corners: UIRectCorner = [.allCorners]
    private var radius: CGFloat = 0

    override func layoutSubviews() {
        super.layoutSubviews()
        self.refreshCorners()
    }

    func roundCorners(corners: UIRectCorner, radius: CGFloat) {
        self.corners = corners
        self.radius = radius
        self.refreshCorners()
    }

    private func refreshCorners() {
        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
    }
}

使用:

let containerView = VariableSeparateCornerView() 
containerView.roundCorners(corners: [.topRight, .bottomLeft, .bottomRight], radius: 20)

答案 1 :(得分:0)

这是扩展版本。可能会更容易。

extension UIView {
   func roundCorners(_ corners:UIRectCorner, radius: CGFloat) {
      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
   }
}

使用:

button?.roundCorners([.topRight, .bottomLeft, .bottomRight], radius: radius)

答案 2 :(得分:0)

您可以尝试这样。

  if #available(iOS 11.0, *) {
        customView.layer.cornerRadius = 10
        customView.layer.maskedCorners = [.layerMinXMaxYCorner,.layerMinXMinYCorner,.layerMaxXMinYCorner]
    } else {
       // Fallback on earlier versions

        let rectShape = CAShapeLayer()
        rectShape.bounds = customView.frame
        rectShape.position = customView.center
        rectShape.path = UIBezierPath(roundedRect: customView.bounds,    byRoundingCorners: [.bottomRight , .topLeft , .topRight], cornerRadii: CGSize(width: 10, height: 10)).cgPath
        customView.layer.mask = rectShape
  }