我有一个黑白图像,其色彩空间由CGColorSpaceCreateDeviceGray()
创建。我想将此图像转换为RGB颜色空间。为此,我向CGContext添加了扩展,如下所示:
extension CGContext {
func convert(to colorSpace: CGColorSpace) -> CGContext {
let rowBytes = self.width * (colorSpace.numberOfComponents + 1)
let context = CGContext(data: nil,
width: width,
height: height,
bitsPerComponent: bitsPerComponent,
bytesPerRow: rowBytes,
space: colorSpace,
bitmapInfo:
CGImageAlphaInfo.premultipliedLast.rawValue)!
let rect = CGRect(x: 0, y: 0, width: self.width, height: self.height)
context.clear(rect)
context.draw(self.makeImage()!, in: rect)
return context
}
}
这很好用,但是感觉应该有一个更好的方法。您对此问题有任何意见吗?