如何将 RGBA 转换为 UIColor 并返回

How convert RGBA to UIColor and back

如何将我的结构 RGBA 转换为 UIColor 并返回

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))))
    }
}

当我使用他的代码时,我的色彩准确度不高

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)
}

怎么了?

欢迎光临!

问题是您使用了两种不同的颜色 spaces:

  • RGBA 转换为 UIColor 时,您假定 RGBA 值在显示 P3 (UIColor(displayP3Red:...) 中。
  • 但据我所知,您使用“设备 RGB”颜色 space 创建的 CGContext 是一种 sRGB 颜色 space。

如果您使用 UIColorinit(red:, green:, blue:, alpha:) 初始值设定项,它应该可以工作。