Tuesday, 7 January 2020

Render a CGImage (rather than UIImage) directly?

Fatass bounty here

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!

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"?



from Render a CGImage (rather than UIImage) directly?

No comments:

Post a Comment