如何将UIColor转换为十六进制字符串? [英] How do I convert a UIColor to a hexadecimal string?
问题描述
我有一个项目,我需要将UIColor的RGBA值作为8字符的十六进制字符串存储在数据库中。例如,[UIColor blueColor]将是@0000FFFF。
我知道我可以得到如下的组件值:
CGFloat r,g,b,a;
[color getRed:& r green:& g blue:& b alpha:& a];
但我不知道如何从这些值转换为十六进制字符串。我已经看到了很多关于如何去其他方面的帖子,但没有什么功能的这种转换。首先将float值转换为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];
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:
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.
Get your floats converted to int values first, then format with 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];
这篇关于如何将UIColor转换为十六进制字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!