直接渲染 CGImage(而不是 UIImage)?

Render a CGImage (rather than UIImage) directly?

我正在做一个CGImage

func otf() -> CGImage {

这是渐变上的贝塞尔蒙版。所以,

    // the path
    let p = UIBezierPath()
    p.moveTo etc

    // the mask
    let m = CAShapeLayer()
    set size etc
    m.path = p.cgPath

    // the layer
    let l = CAGradientLayer()
    set colors etc
    l.mask = m

完成了。然后以通常的方式渲染 UIImage ...

    UIGraphicsBeginImageContextWithOptions(sz.size, false, UIScreen.main.scale)
    l.render(in: UIGraphicsGetCurrentContext()!)
    let r = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

但是。那么要return呢,当然你要转换成CGImage

    return r.cgImage!

(如果你使用类似 ..

UIGraphicsImageRenderer(bounds: b).image { (c) in v.layer.render(in: c) }

..你得到的是 UIImage,而不是 CGImage。)

似乎应该有更好/更优雅的方法 - 有没有什么方法可以更直接地“构建 CGImage”,而不是 "building a UIImage, and then converting"?

需要创建CGContext才能直接生成CGImage

注意:- 使用此代码直接创建CGImage

func createImage() -> CGImage? {
        // the path
        var p = UIBezierPath()
        p = UIBezierPath(arcCenter: CGPoint(x: 100,y: 100), radius: CGFloat(200), startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true)


        // the mask
        let m = CAShapeLayer()
        m.path = p.cgPath

        // the layer
        let layer = CAGradientLayer()
        layer.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
        layer.colors = [UIColor.red.cgColor, UIColor.black.cgColor]
        layer.mask = m



        let imageSize = CGSize(width: 200, height: 200)

        let colorSpace = CGColorSpace(name: CGColorSpace.sRGB)!
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
        guard let context = CGContext(data: nil, width: Int(imageSize.width), height: Int(imageSize.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else { return nil }

        layer.render(in: context)
        let img = context.makeImage()
        return img
    }