CAGradientLayer .conic - is this a bug?

I'm trying to render a CAGradientLayer into a context in order to generate a UIImage in order to generate a SpriteKit texture. If I do it with a standard .axial CAGradientLayer I get no problems. However if I try to use the new .conic type it renders nothing at all. It looks like a bug but since I'm no expert and haven't yet reported any bugs I thought I'd check before reporting it.


Here are the extensions I'm using to SKTexture and UIImage.



import Foundation
import SpriteKit
import UIKit

public extension SKTexture {
    convenience init(gradSize size: CGSize, color1: CGColor, color2: CGColor) {
        let gradientLayer = CAGradientLayer()
        gradientLayer.type = .axial
        gradientLayer.colors = [color1, color2]
        gradientLayer.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        let image = UIImage.imageFromLayer(gradientLayer)
        self.init(cgImage: image.cgImage!)
    } 
}

public extension UIImage {
    
    static func imageFromLayer(_ layer: CALayer) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(layer.bounds.size, layer.isOpaque, 0.0)
        guard let context = UIGraphicsGetCurrentContext() else {
            print("failed to get context")
            UIGraphicsEndImageContext()
            return UIImage()
        }
        layer.render(in: context)
        guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
            print("failed to get image from context")
            UIGraphicsEndImageContext()
            return UIImage()
        }
        UIGraphicsEndImageContext()
        return image
    }
    
}


Then to add it to a scene I use, for example:


        let size = CGSize(width: 100, height: 100)
        let tex = SKTexture(gradSize: size, color1: UIColor.red.cgColor, color2: UIColor.blue.cgColor)
        let example = SKSpriteNode(texture: tex)
        addChild(example)


This works fine until you change line 07 to .conic


Am I doing anything wrong or is this a bug with the new .conic type?

Accepted Reply

Yes, I've filed a report. It's a bug.

Replies

I have the same problem. Have you filed a 🐞 report?

Same here. I'm still investigating, but I think it's a potential bug.

Yes, I've filed a report. It's a bug.

Try using UIView.drawHierarchy(in:afterScreenUpdates:) instead. CALayer.render(in:) only supports functionality that is available from Quartz2D (akd CoreGraphics) and so is often limited by functionaliity that requires the CoreAnimation rendering model.