AjayBhanushali / ABGaugeViewKit

ABGaugeViewKit is a framework which will help you to add Gauge View in your iOS App.
MIT License
27 stars 25 forks source link

CGContextSetStrokeColorWithColor: invalid context 0x0 error in swift #16

Closed pankti28 closed 4 months ago

pankti28 commented 1 year ago

seems like this function

func createArcWith(startAngle: CGFloat, endAngle: CGFloat, arcCap: CGLineCap, strokeColor: UIColor, center:CGPoint) {
        // 1
        let center = center
        let radius: CGFloat = max(bounds.width, bounds.height)/2 - self.frame.width/20
        let lineWidth: CGFloat = self.frame.width/10
        // 2
        let path = UIBezierPath(arcCenter: center,
                                radius: radius,
                                startAngle: startAngle,
                                endAngle: endAngle,
                                clockwise: true)
        // 3
        path.lineWidth = lineWidth
        path.lineCapStyle = arcCap
        strokeColor.setStroke()
        path.stroke()
  }

throws the error for invalid context 0x0

pankti28 commented 1 year ago

Solution:

strokeColor.setStroke()
path.stroke()

These two lines caused the error.

Apparently, You can't do any of those things, in Objective-C or in Swift, unless you are in a graphics context (e.g. drawRect: or UIGraphicsBeginImageContext).

so instead use CAShapeLayer

func createArcWith(startAngle: CGFloat, endAngle: CGFloat, arcCap: CGLineCap, strokeColor: UIColor, center:CGPoint) {
        // 1
        let center = center
        let radius: CGFloat = max(bounds.width, bounds.height)/2 - self.frame.width/20
        let lineWidth: CGFloat = self.frame.width/10
        // 2
        let path = UIBezierPath(arcCenter: center,
                                radius: radius,
                                startAngle: startAngle,
                                endAngle: endAngle,
                                clockwise: true)
        // 3

       let arcLayer = CAShapeLayer()
        arcLayer.path = path.cgPath
        arcLayer.strokeColor = strokeColor.cgColor
        arcLayer.fillColor = UIColor.clear.cgColor

        arcLayer.lineWidth = lineWidth
        layer.addSublayer(arcLayer)
    }