I have a project where I need to store the RGBA values of a UIColor in a database as an 8-character hexadecimal string. For example, [UIColor blueColor] would be @"0000FFFF". I know I can get the component values like so:
我有一个项目,我需要将UIColor的RGBA值作为8个字符的十六进制字符串存储在数据库中。例如,[UIColor blueColor]将是@“0000FFFF”。我知道我可以像这样得到组件值:
CGFloat r,g,b,a;
[color getRed:&r green:&g blue: &b alpha: &a];
but I don't know how to go from those values to the hex string. I've seen a lot of posts on how to go the other way, but nothing functional for this conversion.
但我不知道如何从这些值转到十六进制字符串。我已经看过很多关于如何走另一条路的帖子,但这个转换没有任何功能。
2 个解决方案
#1
21
Get your floats converted to int values first, then format with stringWithFormat
:
首先将浮点数转换为int值,然后使用stringWithFormat格式化:
int r,g,b,a;
r = (int)(255.0 * rFloat);
g = (int)(255.0 * gFloat);
b = (int)(255.0 * bFloat);
a = (int)(255.0 * aFloat);
[NSString stringWithFormat:@"%02x%02x%02x%02x", r, g, b, a];
#2
14
Here it goes. Returns a NSString
(e.g. ffa5678
) with a hexadecimal value of the color.
在这里。返回具有颜色的十六进制值的NSString(例如ffa5678)。
- (NSString *)hexStringFromColor:(UIColor *)color
{
const CGFloat *components = CGColorGetComponents(color.CGColor);
CGFloat r = components[0];
CGFloat g = components[1];
CGFloat b = components[2];
return [NSString stringWithFormat:@"%02lX%02lX%02lX",
lroundf(r * 255),
lroundf(g * 255),
lroundf(b * 255)];
}
#1
21
Get your floats converted to int values first, then format with stringWithFormat
:
首先将浮点数转换为int值,然后使用stringWithFormat格式化:
int r,g,b,a;
r = (int)(255.0 * rFloat);
g = (int)(255.0 * gFloat);
b = (int)(255.0 * bFloat);
a = (int)(255.0 * aFloat);
[NSString stringWithFormat:@"%02x%02x%02x%02x", r, g, b, a];
#2
14
Here it goes. Returns a NSString
(e.g. ffa5678
) with a hexadecimal value of the color.
在这里。返回具有颜色的十六进制值的NSString(例如ffa5678)。
- (NSString *)hexStringFromColor:(UIColor *)color
{
const CGFloat *components = CGColorGetComponents(color.CGColor);
CGFloat r = components[0];
CGFloat g = components[1];
CGFloat b = components[2];
return [NSString stringWithFormat:@"%02lX%02lX%02lX",
lroundf(r * 255),
lroundf(g * 255),
lroundf(b * 255)];
}