本文介绍了直接渲染CGImage(而不是UIImage)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在制作 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
完成。因此,以通常的方式渲染 UIImage
...
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()
但是。然后要返回它,当然必须转换为CGImage
But. Then to return it, of course you have to convert to a CGImage
return r.cgImage!
(如果您使用..
UIGraphicsImageRenderer(bounds: b).image { (c) in v.layer.render(in: c) }
..您得到的是UIImage,而不是CGImage。)
.. you get a UIImage, not a CGImage.)
似乎应该有更好的选择/更优雅的方式-是否有某种方法可以更直接地 构建CGImage ,而不是构建UIImage,然后转换?
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"?
推荐答案
您需要创建CGContext才能生成直接CGImage
You need to create CGContext to generate direct 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
}
这篇关于直接渲染CGImage(而不是UIImage)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!