如何将 NSString 中的十六进制颜色转换为 Objective C 中的三个单独的 rgb 整数?
我可能正在把一些非常简单的事情变得非常复杂,但到目前为止我所尝试的一切似乎都不起作用。
我有像@“BD8F60”这样的NSString,我想将它们转换为整数,例如:r = 189,g = 143,b = 96。
已经找到了将已经是整数的十六进制值转换为rgb整数的方法,但我坚持下去如何将包含字母的 NSString 更改为 int,其中字母已转换为对应的数字。如果这是非常基础的,请提前道歉——我仍然在非常基础的水平上学习这些东西。
I may be making something incredibly simple incredibly complicated, but nothing I've tried so far seems to work.
I have NSStrings like @"BD8F60" and I would like to turn them into ints like: r = 189, g = 143, b = 96.
Have found ways to convert hex values that are already ints into rgb ints, but am stuck on how to change the NSString with the letters in it into an int where the letters have been converted to their numerical counterparts. Apologize in advance if this is incredibly basic--I'm still learning this stuff at an incredibly basic level.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要解析 NSString 并解释十六进制值。
您可以通过多种方式执行此操作,其中一种是使用 NSScanner
还有其他一些可能性,例如将字符串拆分为 3 部分并分别扫描值(而不是进行按位移位和屏蔽),但想法保持不变。
注意:正如
scanHexInt:
文档所解释的,如果您的字符串以0x
为前缀(如@"0xBD8F60"
),这也适用。不会自动处理以哈希为前缀的字符串,例如@"#BD8F60"
。在这种情况下使用子字符串。You need to parse the NSString and interpret the hex values.
You may do this in multiple ways, one being using an NSScanner
There are some other possibilities like splitting the string in 3 and scan the values separately (instead of doing bitwise shift and masking) but the idea remains the same.
Note: as
scanHexInt:
documentation explains, this also works if your string is prefixed with0x
like@"0xBD8F60"
. Does not automatically work with strings prefixed by a hash like@"#BD8F60"
. Use a substring in this case.此方法将给定的十六进制字符串转换为
UIColor
:This method turns the given hex-string into a
UIColor
:UIColor 上的一个类别,还处理 alpha 值 rrggbbaa 和缩写形式如 rgb 或 rgba。
像
或或
或
或
在
swift 中使用它:
#include "UIColor+Creation.h"
到桥接头use
a category on UIColor that also deals with alpha values rrggbbaa and short forms as rgb or rgba.
use it it like
or
or
or
or
use it in swift:
#include "UIColor+Creation.h"
to Bridging Headeruse