CALayers到PNG:奇怪的颜色变化



我的任务是将我的CALayer树渲染为PNG。当我这样做时,我得到的图像通常没问题,但颜色略有变化。

这是我的代码:

我将视图呈现到上下文中

let contentsScale = view.layer!.contentsScale
let width = Int(view.frame.width * contentsScale)
let height = Int(view.frame.height * contentsScale)

let bytesPerRow = width * 4
let context = CGContext(
data: nil,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: bytesPerRow,
space: CGColorSpace(name: CGColorSpace.genericRGBLinear)! ,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
)!
if needsAntialiased {
context.setShouldAntialias(false)
}
view.layer!.render(in: context)

然后我将上下文保存到 PNG 中:

let image = context.makeImage()!
guard let destination = CGImageDestinationCreateWithURL(destinationURL as CFURL, kUTTypePNG, 1, nil) else { return false }
CGImageDestinationAddImage(destination, image, nil)
return CGImageDestinationFinalize(destination)

在某些时候,我的颜色会改变。应填充 B30000 的图层变为 870000。

我想这与色彩空间有关。但我不知道我应该更改通用RGBLinear以保留我的颜色。

有什么想法可以解决问题吗?

因此,解决方案是为相同颜色空间中的图层创建fillColor

let colorSpace = CGColorSpace(name: CGColorSpace.genericRGBLinear)!
layer.fillColor = CGColor(colorSpace: colorSpace, components: components)

最新更新