12

I need to use custom colors in my app. I've found some nice HTML colors and converted them to RGB values then apply them with:

[UIColor colorWithRed:235 green:242 blue:212 alpha:1]

The problem is the resulting color in my app isn't correct. Sometime it's just white and other times it's just way off. Red could be yellow etc.

Has anybody come across this before? Am I converting the colors incorrectly or something.

3 Answers 3

31

Simply divide all you color values by 255:

[UIColor colorWithRed:235/255.0f green:242/255.0f blue:212/255.0f alpha:1]
1
  • 6
    I just wanted to add that the .0f suffix is very important. I used your code without it at first and the color I got was very different. Simply using 57/255 (let's say), doesn't cut it. So to everyone else using this answer, don't forget to add .0f, unlike me :))
    – BBog
    Commented Jan 11, 2012 at 7:48
6

The range of valid values for the parameters to +colorWithRed:green:blue:alpha: is 0 to 1. Assuming your RGB values have the range 0 to 255, your example would be:

[UIColor colorWithRed:0.92f green:0.95f blue:0.83f alpha:1.f];
1
  • Great stuff, thanks. How do I convert the numbers I have to the correct format?
    – jim
    Commented Sep 9, 2011 at 11:47
1

Simply use this method in .m

-(float)getColorValue:(float)colorVal
{
    return colorVal/255;
}

declare definition at .h

-(float)getColorValue:(float)colorVal

Example:

[UIColor colorWithRed:[self getColorValue:227] green:[self getColorValue:227] blue:[self getColorValue:227] alpha:1.0];
1
  • 1
    What a long way to do a simple thing
    – Mutawe
    Commented Mar 1, 2016 at 22:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.