Search code examples
ioscore-graphicsradial-gradients

Radial gradient uses unexpected gray color


TL;DR

Does anyone know how I can smooth out the gradient transition from red to white in a radial gradient? Because I'm getting an ugly gray color in my gradient.

Details:

I created a custom UIView with the following in draw rect

override func draw(_ rect: CGRect) {

    let colors = [UIColor.red.cgColor, UIColor.clear.cgColor] as CFArray
    let divisor: CGFloat = 3
    let endRadius = sqrt(pow(frame.width/divisor, 2) + pow(frame.height/divisor, 2))
    let center = CGPoint(x: bounds.midX, y: bounds.midY)
    let gradient = CGGradient(colorsSpace: nil, colors: colors, locations: nil)

    let context = UIGraphicsGetCurrentContext()
    context?.saveGState()
    context?.drawRadialGradient(gradient!,
                                startCenter: center,
                                startRadius: 0.0,
                                endCenter: center,
                                endRadius: endRadius,
                                options: .drawsBeforeStartLocation)

    context?.restoreGState()
}

I set the custom view's color to red and added the view to the viewcontroller's view, which has a white background.

enter image description here

I wanted the gradient to go from red to white but it seems to go from red to gray. I tried changing the second color in the gradient array to white, and though it did look slightly better, the grayness still remains.

enter image description here


Solution

  • When using clear color on transparent gradients keep in mind that the clear color is generated by applying the black color an alpha and thats why you get the greyish color on your case.

    To solve this in your code change UIColor.clear.cgColor, from colors array, with UIColor.white.withAlphaComponent(0.0).cgColor. This way you can get the gradient you expect.