I've been struggling to export an MTLTexture that uses BGRA10_XR (for P3) to a CGImage/UIImage that matches the same colors displayed in the MTLTexture (or on screen).
Code Block Swift func getImage() -> UIImage? { let bufferWidth: Int = Int(size.width) let bufferHeight: Int = Int(size.height) let bytesPerRow: Int = Int(ceilf(self.size.width * 4/32)) * Int(32) let bufferSize: Int = bytesPerRow * bufferHeight; let colorspace: CGColorSpace let bitmapInfo: CGBitmapInfo let bitsPerComponent: Int let bitsPerPixel: Int if self.isBGRA10_XR { bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue).union(.byteOrder16Little) bitsPerComponent = 16 bitsPerPixel = 64 colorspace = CGColorSpace(name: CGColorSpace.displayP3)! } else { bitmapInfo = CGBitmapInfo(rawValue: (CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.first.rawValue)) bitsPerComponent = 8 bitsPerPixel = 32 colorspace = CGColorSpaceCreateDeviceRGB() } let data = malloc(bufferSize) memcpy(data, self.mtlTextureBuffer.contents(), bufferSize) provider = CGDataProvider(dataInfo: nil, data: data!, size: bufferSize, releaseData: { info, data, size in free(UnsafeMutableRawPointer(mutating: data)) })! guard let image = CGImage(width: bufferWidth, height: bufferHeight, bitsPerComponent: bitsPerComponent, bitsPerPixel: bitsPerPixel, bytesPerRow: bytesPerRow, space: colorspace, bitmapInfo: bitmapInfo, provider: provider, decode: nil, shouldInterpolate: false, intent: .relativeColorimetric) else { return nil } let scale = useScale ? UIScreen.main.scale : 1 let img = UIImage(cgImage: image, scale: scale, orientation: .up) return img }