Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

How can I convert RGB hex string into UIColor in objective-c?

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 ...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

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]]; 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...