How convert RGBA to UIColor and back

Viewed 390

How can i convert my struct RGBA to UIColor and back

struct RGBA {
    
    var r: UInt8
    var g: UInt8
    var b: UInt8
    var a: UInt8

    var toUIColor: UIColor {
        let red = CGFloat(r) / CGFloat(255)
        let green = CGFloat(g) / CGFloat(255)
        let blue = CGFloat(b) / CGFloat(255)
        let alpha = CGFloat(a) / CGFloat(255)
        
        return UIColor(displayP3Red: CGFloat(red),
                       green: CGFloat(green),
                       blue: CGFloat(blue),
                       alpha: CGFloat(alpha))
    }
}
extension UIColor {
    
    var toRGBA: RGBA {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0
        getRed(&red, green: &green, blue: &blue, alpha: &alpha)

        return RGBA(r: UInt8(max(0, min(255, red * 255))),
                    g: UInt8(max(0, min(255, green * 255))),
                    b: UInt8(max(0, min(255, blue * 255))),
                    a: UInt8(max(0, min(255, alpha * 255))))
    }
}

When I use t his code, im loose color accuracy

Draw pipline
select UIColor -> toRGBA ->
0.7490196078431373 0.35294117647058826 0.9490196078431372 1.0

select color on canvas -> toUIColor
draw line -> toRGBA -> 
0.803921568627451 0.3215686274509804 0.9803921568627451 1.0
var canvasSize = PixelSize(width: 16, height: 16) //  (Int, Int)

func createImage(by pixels: [RGBA]) -> UIImage? {
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let data = UnsafeMutableRawPointer(mutating: pixels)

    let bitmapContext = CGContext(data: data,
                                  width: canvasSize.width,
                                  height: canvasSize.height,
                                  bitsPerComponent: 8,
                                  bytesPerRow: 4 * canvasSize.width,
                                  space: colorSpace,
                                  bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)

    guard let image = bitmapContext?.makeImage() else { return nil }
    return UIImage(cgImage: image)
}

Whats wrong?

1 Answers

Welcome!

The issue is that you use two different color spaces:

  • When converting from RGBA to UIColor, you assume the RGBA values are in Display P3 (UIColor(displayP3Red:...).
  • But the CGContext you create with the "device RGB" color space, which is an sRGB color space as far as I know.

If you'd use the init(red:, green:, blue:, alpha:) initializer of UIColor it should work.

Related