【问题标题】:Top right and top left corner radius is not working properly右上角和左上角半径无法正常工作
【发布时间】:2020-04-10 07:37:56
【问题描述】:

我只想为顶角添加圆角半径,当我将圆角半径添加到顶角时,整个视图的宽度都在变化,下面是我使用的代码。

func roundCorners(corners: UIRectCorner, radius: CGFloat) {
     let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
     let mask = CAShapeLayer()
     layer.mask = mask
     mask.path = path.cgPath
     layer.masksToBounds = true
}

当我为整个图层添加圆角半径时,它工作正常,

图层视图.layer.cornerRadius = 半径

但我只想要顶角半径如何在不影响视图宽度的情况下做到这一点

【问题讨论】:

  • 我刚刚尝试了您的功能,它在标准UIButton 上运行良好,但您使用的按钮可能有问题?如果您包含相关的自定义按钮代码(它的布局是如何构建的)会有所帮助

标签: ios swift uiview cornerradius


【解决方案1】:

您可以使用以下函数来实现该行为

func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
        let maskPath = UIBezierPath(
            roundedRect: bounds,
            byRoundingCorners: corners,
            cornerRadii: CGSize(width: radius, height: radius))

        let shape = CAShapeLayer()
        shape.path = maskPath.cgPath
        layer.mask = shape
    }

然后像这样简单地使用它

someview.roundCorners([.topLeft, .topRight], radius: 25)

但应用圆角半径的关键在于应用的时间!!您可以在 ViewDidAppear 或 layoutsubviews 方法中应用它。基本上在那些你确定你会得到视图的准确宽度和高度的地方。谢谢!!

【讨论】:

    【解决方案2】:

    使用这个扩展

    extension UIView 
    {
    
       @discardableResult func _round(corners: UIRectCorner, radius: CGFloat) -> CAShapeLayer {
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
        return mask
       }
    
    func addBorder(mask: CAShapeLayer, borderColor: UIColor, borderWidth: CGFloat) {
        let borderLayer = CAShapeLayer()
        borderLayer.path = mask.path
        borderLayer.fillColor = UIColor.clear.cgColor
        borderLayer.strokeColor = borderColor.cgColor
        borderLayer.lineWidth = borderWidth
        borderLayer.frame = bounds
        layer.addSublayer(borderLayer)
    }
    
    func round(corners: UIRectCorner, radius: CGFloat, borderColor: UIColor, borderWidth: CGFloat) {
        let mask = _round(corners: corners, radius: radius)
        addBorder(mask: mask, borderColor: borderColor, borderWidth: borderWidth)
    }
    }
    

    你可以通过下面的代码调用

     self.yourView.round(corners: [.topLeft,.topRight], radius: 20, borderColor: .clear, borderWidth: 0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      • 2016-06-08
      • 1970-01-01
      • 2023-03-25
      • 2020-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多