How can the CALayerGradient conic be rendered?

Viewed 340

I'm trying to render a conic gradient using CALayerGradient in a CGContext

    let colors = [ UIColor(hue: 0, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor,
                   UIColor(hue: 1/6, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor,
                   UIColor(hue: 2/6, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor,
                   UIColor(hue: 0.5, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor,
                    UIColor(hue: 4/6, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor,
                    UIColor(hue: 5/6, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor,
                    UIColor(hue: 1.0, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor ]

    let conicGradient = CAGradientLayer()
    conicGradient.type = .conic
    conicGradient.frame = bounds
    conicGradient.startPoint = CGPoint( x: 0.5, y: 0.5 )
    conicGradient.endPoint = CGPoint( x: 1, y: 1 )
    conicGradient.colors = colors as [Any]

    conicGradient.render( in: mContext ) // This doesn't work

    if let drawingContext = UIGraphicsGetCurrentContext()
    {
        drawingContext.draw( myContext.makeImage()!, in: bounds )
    }

Above, changing type to anything else will work. Also, if i don't try rendering to CGContext, but add this as a sublayer, it works, the only thing that doesn't work, is the conic rendered in a CGContext, which is the thing i want to do. So is there something i'm missing, or is the rendering of conic not implemented ?

1 Answers

Instead of trying to render into an arbitrary context, try pushing that context using UIGraphicsPushContext(_:), drawing into the now-current context, and then popping that context off with UIGraphicsPopContext().

Related