Render a CGImage (rather than UIImage) directly?

人走茶凉 提交于 2020-01-16 02:26:44

问题


I'm making a CGImage

func otf() -> CGImage {

which is a bezier mask on a gradient. So,

    // 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

it's done. So then render a UIImage in the usual way ...

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

But. Then to return it, of course you have to convert to a CGImage

    return r.cgImage!

(Same deal if you use something like ..

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

.. you get a UIImage, not a CGImage.)

Seems like there should be a better / more elegant way - is there some way to more directly "build a CGImage", rather than "building a UIImage, and then converting"?


回答1:


You need to create CGContext to generate direct CGImage

Note:- Use this code to create direct 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
    }


来源:https://stackoverflow.com/questions/59592933/render-a-cgimage-rather-than-uiimage-directly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!