如何在Objective-C中将RGB十六进制字符串转换为UIColor? [英] How can I convert RGB hex string into UIColor in objective-c?
问题描述
我有一些来自url数据的颜色值,例如#ff33cc".如何将该值转换为UIColor?我正在尝试以下代码行.我没有得到正确的baseColor1值.看来我应该把那磅英镑掉了.还有另一种方法吗?
I have color values coming from the url data is like this, "#ff33cc". How can I convert this value into UIColor? I am attempting with the following lines of code. I am not getting the value for baseColor1 right. Looks like I should take that pound char off. Is there another way to do it?
NSScanner *scanner2 = [NSScanner scannerWithString:@"#ff33cc"];
int baseColor1;
[scanner2 scanHexInt:&baseColor1];
CGFloat red = (baseColor1 & 0xFF0000);
[UIColor colorWithRed:red ...
推荐答案
You're close but colorWithRed:green:blue:alpha: expects values ranging from 0.0 to 1.0, so you need to shift the bits right and divide by 255.0f:
CGFloat red = ((baseColor1 & 0xFF0000) >> 16) / 255.0f;
CGFloat green = ((baseColor1 & 0x00FF00) >> 8) / 255.0f;
CGFloat blue = (baseColor1 & 0x0000FF) / 255.0f;
编辑-NSScanner的scanHexInt也会跳过十六进制字符串前面的0x,但我认为它不会跳过十六进制字符串前面的#字符.您可以添加以下行来处理该问题:
EDIT - Also NSScanner's scanHexInt will skip past 0x in front of a hex string, but I don't think it will skip the # character in front of your hex string. You can add this line to handle that:
[scanner2 setCharactersToBeSkipped:[NSCharacterSet symbolCharacterSet]];
这篇关于如何在Objective-C中将RGB十六进制字符串转换为UIColor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!