Search code examples
swiftgradientcalayercashapelayer

Gradient Arc View Not Showing Correctly


i have a custom view that is a 85% of a circle ( Just Stroke ) with Gradient color . here is my code :

class ProfileCircle:UIView
{
override func draw(_ rect: CGRect)
    {
            let desiredLineWidth:CGFloat = 4    // your desired value
            let arcCenter = CGPoint(x: self.bounds.midX, y: self.bounds.midY)

            let radius = self.bounds.midX


        let circlePath = UIBezierPath(
            arcCenter: arcCenter,
            radius: radius,
            startAngle: CGFloat(0),
            endAngle:CGFloat((.pi * 2)*0.85),
            clockwise: true)

        let shapeLayer = CAShapeLayer()
            shapeLayer.lineCap = .round
            shapeLayer.path = circlePath.cgPath
            shapeLayer.fillColor = UIColor.clear.cgColor
            shapeLayer.strokeColor = UIColor.red.cgColor
            shapeLayer.lineWidth = desiredLineWidth

            let gradient = CAGradientLayer()
            gradient.frame = circlePath.bounds
            gradient.colors = [UIColor.colorPrimary.cgColor, UIColor.colorSecondary.cgColor]

        //layer.addSublayer(shapeLayer)
            gradient.mask = shapeLayer
            layer.addSublayer(gradient)

}

}

but the edges are clipped

a

i have tried a lot but i cant fix it .

one more thing is that when i change the radius manually the view wont be centered


Solution

  • Just two changes:

    let radius = self.bounds.midX - desiredLineWidth
    

    and

    gradient.frame = self.bounds