Reputation: 89
My task is to render my CALayer tree to PNG. When I do this I get the image which is generally OK, but the colors slightly change.
Here's my code:
I render the view into context
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)
And then I save the context into 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)
At some point my colors change. The layer that should be filled with B30000 becomes 870000.
I suppose it has something to do with colorspace. But I don't know what should I change genericRGBLinear for to preserve my colors.
Any ideas where the problem can be?
Upvotes: 0
Views: 79
Reputation: 89
So the solution was to create fillColor for layer in the same color space
let colorSpace = CGColorSpace(name: CGColorSpace.genericRGBLinear)!
layer.fillColor = CGColor(colorSpace: colorSpace, components: components)
Upvotes: 1