Search code examples
iosswiftswift3uicolorcgpath

How to set the color for shape in cgmutablepath?


I am using cgmutablepath to draw a polygon where i would like to fill color for the polygon but it is not working and i have no idea why...

Below is my code:

var path = CGMutablePath()
        path.move(to: CGPoint(x: 127.5, y: 12.5))
        path.addLine(to: CGPoint(x: 165.0, y: 13.0))
        path.addLine(to: CGPoint(x: 165.0, y: 50.5))
        path.addLine(to: CGPoint(x: 127.5, y: 50.5))
        path.closeSubpath()

       var shape = CAShapeLayer()
       shape.path = path
       shape.lineWidth = 3.0
       shape.strokeColor = UIColor.blue.cgColor
       shape.fillColor = UIColor.blue.cgColor

Solution

  • Try replacing your code with this updated code :

        var path = CGMutablePath()
        path.move(to: CGPoint(x: 127.5, y: 12.5))
        path.addLine(to: CGPoint(x: 165.0, y: 13.0))
        path.addLine(to: CGPoint(x: 165.0, y: 50.5))
        path.addLine(to: CGPoint(x: 127.5, y: 50.5))
        path.closeSubpath()
    
       var shape = CAShapeLayer()
       shape.path = path
       shape.lineWidth = 3.0
       shape.strokeColor = UIColor.blue.cgColor
       shape.fillColor = UIColor.blue.cgColor
       self.layer.addSublayer(shapeLayer)
    

    Please try it out and comment in case of any error. Happy Coding.