3

I try to add a CAGradient effect in a pie chart I make with Core Graphics. It turns out I am not able and certainly not understand very well how to apply it to a view that is part of a CGPath...

override func draw(_ rect: CGRect)
    {
    ...
    func arc(myRadius: CGFloat, myStartAngle: CGFloat, myEndAngle: CGFloat) {
        // This is the pie chart segment
        context?.setFillColor(phenotypeColor.cgColor)
        context?.move(to: center)
        context?.addArc(center: center, radius: finalRadius, startAngle: myStartAngle, endAngle: myEndAngle, clockwise: true)
        context?.fillPath()

        (...)
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = self.bounds
        gradientLayer.colors = [UIColor.red, UIColor.blue]
        self.layer.addSublayer(gradientLayer)
    }

I don't see any gradient on the screen (only the white background...). Lastly, I also tried to clip the context juste after saving its state but I am not sure I clip anything since I don't see any gradient (either on the whole view or just on the segment). I read the documentation but it does not clear things up (in my case...).

Trichophyton
  • 625
  • 5
  • 21
  • Have you added startPoint and endPoint ? – Sagar Chauhan Mar 15 '17 at 12:23
  • It is in fact working without the start/endpoint. I was missing the .cgcolor when defining colors. But I don't know how I can apply this gradient to a segment of my chart (defined with the .addArc method). I cannot get a view or a path from it. Any idea? – Trichophyton Mar 15 '17 at 13:21
  • You should edit your question to reflect what you are now asking... A quick search finds this link, which is probably all you need: http://stackoverflow.com/questions/23202228/how-to-fill-a-uibezierpath-with-a-gradient – DonMag Mar 15 '17 at 13:28
  • I will have a look. I have been searching a lot of internet pages, but I have not found this one. Thanks! – Trichophyton Mar 15 '17 at 15:31
  • 1
    If the problem is solved, don't edit the _question_ to show the answer; _answer_ your own question (perfectly legal on Stack Overflow), and in a couple of days you can _accept_ your answer to close the question. If this raises a _new_ question, ask it as a _separate question_. – matt Mar 15 '17 at 15:54

1 Answers1

7

cgColor was missing... Sorry for the inconvenience.

let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.bounds
gradientLayer.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]
self.layer.addSublayer(gradientLayer)
Trichophyton
  • 625
  • 5
  • 21
  • 2
    No need to apologize. We've all done it. When you make this mistake, you get no error message and everything just fails silently. It's maddening! – matt Mar 15 '17 at 17:08