adding bezierpath inside UIView Container

427 Views Asked by At

I am trying to add a bezierpath(triangle shaped) inside(bottom) an UIView container however I cant seem to get the point correctly of the UIView Container. I am getting this for a result(where is seems a strip of the triangle is showing to the left of the Container View ): enter image description here

I would like an output such as :

enter image description here

this is my code thus far :

   // adding container to add image
        self.topContainer.backgroundColor = UIColor(red: 49/255, green:  207/255, blue: 203/255, alpha: 1)
        //        self.topContainer.backgroundColor = UIColor.white
        self.topContainer.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(self.topContainer)


        self.topContainer.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        self.topContainer.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.55).isActive = true
        self.topContainer.widthAnchor.constraint(equalTo: view.widthAnchor).isActive =  true

        let bezierPath = UIBezierPath()                
        bezierPath.move(to: CGPoint(x: 0, y: self.topContainer.frame.size.height))
        bezierPath.addLine(to: CGPoint(x: self.topContainer.frame.size.width, y: 222))
        bezierPath.addLine(to: CGPoint(x: self.topContainer.frame.size.width, y: self.topContainer.frame.size.height))
        bezierPath.addLine(to: CGPoint(x: 0, y: self.topContainer.frame.size.height))

        UIColor.white.setFill()
        bezierPath.fill()
        bezierPath.lineWidth = 1
        bezierPath.close()

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = bezierPath.cgPath
        shapeLayer.lineWidth = 2.0
        shapeLayer.strokeColor = UIColor.white.cgColor
        shapeLayer.fillColor = UIColor.white.cgColor
        self.topContainer.layer.addSublayer(shapeLayer)
1

There are 1 best solutions below

4
On

You are apparently doing this code in viewDidLoad of a view controller. You should:

  • Remove the UIColor.white.setFill() and path.fill() code. That only makes sense if drawing within a graphics context (e.g. draw method of a UIView or within a UIGraphicsBegin/EndImageContext). Just construct the CAShapeLayer and add it to the view/layer hierarchy, and the OS will take care of drawing/filling it for you.

  • Go ahead and create and configure the CAShapeLayer in viewDidLoad, but move the creation of the UIBezierPath and the setting of the CAShapeLayer's path to the view controller's viewDidLayoutSubviews method. The frame of the view is generally unknown during viewDidLoad and is certainly susceptible to being changed (via constraints or autosizing masks). By the time viewDidLayoutSubviews is called, the frame is properly configured (and will get called again if the frame of the main view changes).