Mini2008
Mini2008

Reputation: 677

CGGradient now drawing exact color on UIBazierPath

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

Upvotes: 2

Views: 1098

Answers (1)

Schemetrical
Schemetrical

Reputation: 5536

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".

Upvotes: 1

Related Questions