Search code examples
iosswiftuibezierpath

How to set Corner Radius to UIBezierPath


I have created following image by UIBezierPath using this code

    //// Bezier Drawing
    let bezierPath = UIBezierPath()
    bezierPath.move(to: CGPoint(x: 360, y: 0))
    bezierPath.addCurve(to: CGPoint(x: 360, y: 75), controlPoint1: CGPoint(x: 359.53, y: 30.5), controlPoint2: CGPoint(x: 359.91, y: 55.45))
    bezierPath.addCurve(to: CGPoint(x: 360, y: 153.78), controlPoint1: CGPoint(x: 360.35, y: 153.21), controlPoint2: CGPoint(x: 360, y: 153.78))
    bezierPath.addCurve(to: CGPoint(x: 180, y: 153.78), controlPoint1: CGPoint(x: 360, y: 153.78), controlPoint2: CGPoint(x: 271.2, y: 212.77))
    bezierPath.addCurve(to: CGPoint(x: 0, y: 153.78), controlPoint1: CGPoint(x: 88.8, y: 94.8), controlPoint2: CGPoint(x: 0, y: 153.78))
    bezierPath.addLine(to: CGPoint(x: 0, y: 0))
    bezierPath.addLine(to: CGPoint(x: 360, y: 0))
    UIColor.green.setFill()
    bezierPath.fill()

enter image description here

now i want to give corner radius to TopLeft and TopRight of this following Image using Slider.

I have Tried Following code but it did not works for me.

        var cornerPath = path

        cornerPath = UIBezierPath(roundedRect:self.imgTop.bounds,
                                          byRoundingCorners:[.topLeft, .topRight],
                                          cornerRadii: CGSize(width: CGFloat(cornerRadius),
                                                              height: CGFloat(cornerRadius)))

        path.lineWidth = 1.0

        let maskLayer = CAShapeLayer()
        maskLayer.path = cornerPath.cgPath
        self.imgTop.layer.mask = maskLayer

    let maskLayerTop = CAShapeLayer()
    maskLayerTop.fillColor = UIColor.white.cgColor
    maskLayerTop.backgroundColor = UIColor.clear.cgColor
    maskLayerTop.path = pathTop?.cgPath
    maskLayerTop.cornerRadius = CGFloat(cornerRadius)
    //maskLayerTop.masksToBounds = true

    maskLayerTop.shadowRadius = CGFloat(cornerRadius)
    maskLayerTop.fillColor = UIColor.green.cgColor
    maskLayerTop.shadowColor = UIColor.blue.cgColor

    imgTop.layer.mask = maskLayerTop

I had also tried to applying corner radius to Image view but it did not work.i want corner radius like following image.

enter image description here

Please Help! .

.

NOTE: I had already create one path to create following Image


Solution

  • before your let bezierPath = UIBezierPath() for curve add

    var = cornerRadiudSize = CGSize(width: 50.0, height: 50.0) //this is your global variable that you can change based on the slider and then draw
    let p = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: cornerRadiudSize)
    p.addClip()
    

    PS: Instead of all corner set the corners you want

    image worth a thousand words