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 ):
I would like an output such as :
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)
You are apparently doing this code in
viewDidLoad
of a view controller. You should:Remove the
UIColor.white.setFill()
andpath.fill()
code. That only makes sense if drawing within a graphics context (e.g.draw
method of aUIView
or within aUIGraphicsBegin/EndImageContext
). Just construct theCAShapeLayer
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
inviewDidLoad
, but move the creation of theUIBezierPath
and the setting of theCAShapeLayer
'spath
to the view controller'sviewDidLayoutSubviews
method. Theframe
of the view is generally unknown duringviewDidLoad
and is certainly susceptible to being changed (via constraints or autosizing masks). By the timeviewDidLayoutSubviews
is called, theframe
is properly configured (and will get called again if theframe
of the main view changes).