问题
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