如何从十六进制值转换为 UIColor?
我有一个十六进制颜色值,我想将其转换为 UIColor。 UIColor 可以接受色相/饱和度/亮度 (HSB) 值或红/蓝/绿 (RGB) 值。如何使用十六进制值创建 UIColor?
I have a hexadecimal color value and I want to convert it to a UIColor. UIColor can take in a Hue/Saturation/Brightness (HSB) value or a Red/Blue/Green (RGB) value. How can I use the hex value to create a UIColor?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不久前从某个地方捡到了这个,它已经在我所有项目的宏标题中有一段时间了。
使用方法:view.backgroundColor = UIColorFromRGB(0x2134b6)
Picked this up from somewhere a while back, it's been sitting in my macro header for all my projects for a while now.
To use: view.backgroundColor = UIColorFromRGB(0x2134b6)
有一个很棒的免费库,基本上只是 UIColor 的一些附加组件 这里 (我认为这是我用的是同样的东西,记不清了)。检查一下以确保,但我认为它有您正在寻找的东西。
There is a great free library that is basically just some add ons to UIColor here (i think this is the same thing I use, cant remember). Check it out to make sure, but I think it has what you are looking for.
请参阅如何创建的答案来自十六进制字符串的 UIColor?
基本概念是获取十六进制字符串的红蓝绿部分,将它们除以 256,然后得到 UIColor 所需的 [0, 1] 红蓝绿值。
忘记 HSB 值,您不需要进行该转换。
See the answers to How can I create a UIColor from a hex string?
The basic concept is to take the red blue green segments of the hex string, divide them by 256, and there you have your [0, 1] red blue green values that UIColor needs.
Forget the HSB values, you don't need to make that conversion.
我不确定你的颜色值是如何编码在十六进制值中的。但这里有一个 RGB 值的示例。假设您有一个编码为 hexRGB = 0xRRGGBB 的十六进制值,将其分配给 UIColor,您所要做的就是
如果从值编码为 0xHHSSBB 的十六进制读取 HSB 值,则可以使用相同的技术
I'm not sure how your color value is encoded in the HEX value. But here's an example with RGB values. Let's say you have a HEX value encoded something like this hexRGB = 0xRRGGBB to assign it to a UIColor, all you would have to do is
The same technique could be used if reading a HSB value from hex where the value is encoded: 0xHHSSBB
正如其他人提到的,你的十六进制值可能是 RGB。
我需要为我发现以编程方式创建按钮突出显示的方法执行此操作一次。 HSB(或也称为 HSV)背后的理论在 wikipedia 中有详细讨论。颜色空间的所有数学知识都在那里,因此如果实现您自己的颜色空间,它可能是起点。
罗彻斯特理工学院有一个很好的、紧凑的、简单的 C 实现。 您应该能够将这些函数粘贴进去并直接使用它们。
(但是,如果 Erica Sadun 在 UIColor 中编写了一个类别来提供此功能,请使用它。请参阅 Jesse Naugher 的回答以获取链接。)
As others have mentioned your HEX values are probably RGB.
I needed to do this once for a method I found that created button highlights programmatically. The theory behind HSB (or HSV as it is also known) is discussed in great detail at wikipedia. All the mathematics of the color space is there so if implementing your own it's probably the place to start.
There's a nice, compact, simple implementation in C at Rochester Institute of Technology. You should be able to paste these functions in and use them directly.
(But if Erica Sadun wrote a category to provide this function in UIColor, use it. See Jesse Naugher's answer for link.)