从 UIExtendedSRGBColorSpace 转换为十六进制 [英] Converting from UIExtendedSRGBColorSpace to Hex

查看:87
本文介绍了从 UIExtendedSRGBColorSpace 转换为十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的框架以 UIExtendedSRGBColorSpace 格式输出颜色.我需要向用户和仅接受六字符十六进制代码的后端应用程序显示此输出颜色的六字符十六进制值.我尝试了许多转换方法,但它们似乎都导致奇怪的十六进制值.例如,获取输出 UIExtendedSRGBColorSpace 0.276088 -0.0525 1.05 1 并使用像 this(我之前已经成功使用过多次)导致 46FFFFFFFFFFFFFFF310C.简单地将 UIExtendedSRGBColorSpace 输出应用为按钮/视图上的背景颜色没有问题,但它获得了问题颜色的十六进制值.

I'm using a framework that outputs colour in the UIExtendedSRGBColorSpace format. I need to display a six character hex value for this output colour to the user and for a backend application that only accepts six-character hex codes. I've tried numerous conversion methods but they all seem to result in odd hex values. For example, getting an output UIExtendedSRGBColorSpace 0.276088 -0.0525 1.05 1 and using an extension like this (which i've used successfully many times before) results in 46FFFFFFFFFFFFFFF310C. There are no issues with simply applying the UIExtendedSRGBColorSpace output as a background colour on a button/view, but its getting a hex value of the colour that is the problem.

如果对此的任何解决方案会导致颜色准确性的某种形式的损失,只要我能够获得模糊相似的十六进制代码就可以了.我对编程非常陌生,花了很多时间试图理解这一点,但运气不佳,因此感谢您的帮助!

It would be fine if any solution to this leads to some form of loss in colour accuracy, as long as i'm able to get a vaguely similar hex code. I'm very new to programming and have spent quite some time trying to understand this with no luck, so appreciate any help!

推荐答案

您可以将 UIColor 转换为 CGColor 并从 eRGB 转换为 sRGB.请注意,一旦将其转换为标准 RGB,就无法再转换回扩展 RGB:

You can convert your UIColor to CGColor and convert from eRGB to sRGB. Note that once you convert it to standard RGB you can't convert back to extended RGB:

extension CGColorSpace {
    static let sRGB = CGColorSpace(name: CGColorSpace.sRGB)!
    static let extendedSRGB = CGColorSpace(name: CGColorSpace.extendedSRGB)!
}


extension CGColor {
    var color: UIColor { .init(cgColor: self) }
}


extension UIColor {
    var extendedSRGB2sRGB: UIColor? {
        guard let components = cgColor.components else { return nil }
        return CGColor(colorSpace: .extendedSRGB, components: components)?
            .converted(to: .sRGB, intent: .relativeColorimetric, options: nil)?.color
    }
}


游乐场测试:


Playground testing:

let extendedSRGB = UIColor(red: 0.276088, green: -0.0525, blue: 1.05, alpha: 1)
let sRGB = extendedSRGB.extendedSRGB2sRGB  // r 0.276 g 0.0 b 1.0 a 1.0

这篇关于从 UIExtendedSRGBColorSpace 转换为十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆