2

I am using CGGradiant to draw a gardiant 3/4 cirlce using three colors starting with red to yellow to green. But CGGradiant always starting color from slightly yellow rather than red. I am using its because the start/end point i am giving in drawLinearGradient.But not sure what to do give then. Below is the code and attached result. Any suggestion would be helpful.

     let path1 = UIBezierPath(arcCenter: center,
                             radius: radius-20,
                             startAngle: startAngle,
                             endAngle: endAngle,
                             clockwise: false)

    let strokedPath = path1.cgPath.copy(strokingWithWidth: strokeWidth, lineCap: .butt, lineJoin: .miter, miterLimit: 0)
    ctx!.addPath(strokedPath)
    ctx?.clip()
    let red = UIColor(red: 234.0/255.0, green: 34.0/255.0, blue: 34.0/255.0, alpha:1)
    let green = UIColor(red: 254.0/255.0, green: 187.0/255.0, blue: 3.0/255.0, alpha:1)
    let blue = UIColor(red: 69.0/255.0, green: 207.0/255.0, blue: 51.0/255.0, alpha:1)

    let gradient = CGGradient(
        colorsSpace: CGColorSpaceCreateDeviceRGB(),
        colors: [red.cgColor, green.cgColor,blue.cgColor] as CFArray,
        locations: [0,0.5,1]
    )

    context!.drawLinearGradient(
        gradient!,
        start: CGPoint(x: 20, y: 20),
        end: CGPoint(x: rect.width-10, y: rect.height-10),
        options: []
    )

Gradiant circle

Mini2008
  • 627
  • 1
  • 6
  • 12

1 Answers1

1

Your gradient is not the right type. Right now the gradient starts from the top left and travels to the bottom right. This is called a linear gradient.

Linear gradient

This is why you see red on the top left, yellow in the top right and bottom left, and green on the bottom right.

What you want is a conic gradient, similar to the following image.

Conic gradient

Unfortunately CGGradient does not define simple methods to create this (as this SO page says), so use one of the recommended frameworks or google for one using the term "iOS conic gradient".

Schemetrical
  • 5,506
  • 2
  • 26
  • 43
  • Thanks for your comment, yeah i understand that its not conic but linear but wondering if by placing some values around i can get the desired result. – Mini2008 Aug 02 '18 at 09:00
  • @Mini2008 I cannot think of anything obvious from the top of my head unfortunately. – Schemetrical Aug 02 '18 at 15:20