Search code examples
iosswift3uiviewuibezierpathcashapelayer

UIView with UIBezierPath with reversing path


I am trying to give some mask at bottom view using UIBezierPath with addCurve() method.

Expected Result

enter image description here

Current Output

enter image description here

What I have tried is:

        viewHeader.backgroundColor = headerColor
        let path = UIBezierPath()
        let cpoint1 = CGPoint(x: 80, y: 160)
        let cpoint2 = CGPoint(x: 280, y: viewHeader.Height + 50)
        path.move(to:.init(x: 0, y: viewHeader.Height + 10))
        path.addCurve(to: .init(x: viewHeader.Width, y: 205), controlPoint1: cpoint1, controlPoint2: cpoint2)
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path.reversing().cgPath
        shapeLayer.fillColor = headerColor?.cgColor
        shapeLayer.strokeColor =  UIColor.black.cgColor
        shapeLayer.lineWidth = 1.0
        viewHeader.layer.addSublayer(shapeLayer)

Solution

  • I hope it ll work for you, enjoy.

    func drawLine() {
        let headerColor = UIColor.red
        let path = UIBezierPath()
        let cpoint1 = CGPoint(x: viewHeader.frame.width/4, y: 160)
        let cpoint2 = CGPoint(x: viewHeader.frame.width*3/4, y: viewHeader.frame.height + 50)
        path.move(to:.init(x: 0, y: 0))
        path.addLine(to:.init(x: 0, y: viewHeader.frame.height - 50))
        path.addCurve(to: .init(x: viewHeader.frame.width, y: viewHeader.frame.height - 50), controlPoint1: cpoint1, controlPoint2: cpoint2)
        path.addLine(to: CGPoint(x: viewHeader.frame.width, y: 0))
        path.addLine(to: CGPoint(x: 0, y: 0))
        path.close()
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path.reversing().cgPath
        shapeLayer.fillColor = headerColor.cgColor
        shapeLayer.strokeColor =  headerColor.cgColor
        shapeLayer.lineWidth = 1.0
        viewHeader.layer.addSublayer(shapeLayer)
    }