iosuiviewcornerradius

Different cornerRadius for each corner


I want to set different corner radius for a view in iOS. I am able to set the radius for each corner to the same value like the one mentioned in the following post How to set cornerRadius for only top-left and top-right corner of a UIView?

Is there a way I can set the corner radius in the following format?

Radius top-left: 18
Radius top-right: 18
Radius bottom-right: 3
Radius bottom-left: 18


Solution

  • You could set the default layer.cornerRadius to the smallest value and then set the layer mask's border to the bigger value.

    let demoView = UIView(frame: CGRect(x: 100, y: 200, width: 100, height: 100))
    demoView.backgroundColor = UIColor.red
    demoView.layer.cornerRadius = 3.0
    
    let maskPath = UIBezierPath(roundedRect: demoView.bounds,
                                byRoundingCorners: [.topLeft, .topRight, .bottomLeft],
                                cornerRadii: CGSize(width: 18.0, height: 0.0))
    
    let maskLayer = CAShapeLayer()
    maskLayer.path = maskPath.cgPath
    demoView.layer.mask = maskLayer
    view.addSubview(demoView)