0

I need to assign user profiles colors in a pseudo random consistent way based on their username/name/any string.

How do I do this in objective C iOS 7?

Java based example is here

Compute hex color code for an arbitrary string

Community
  • 1
  • 1
kevin
  • 4,177
  • 10
  • 32
  • 33

2 Answers2

5

There are probably many ways. Here's one:

NSString *someString = ... // some string to "convert" to a color
NSInteger hash = someString.hash;
int red = (hash >> 16) & 0xFF;
int green = (hash >> 8) & 0xFF;
int blue = hash & 0xFF;
UIColor *someColor = [UIColor colorWithRed:red / 255.0 green:green / 255.0 blue:blue / 255.0 alpha:1.0];

The same string will always give the same color. Different strings will generally give different colors but it is possible that two different strings could give the same color.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
0

My version:

+ (UIColor *)colorForString:(NSString *)string
{
    NSUInteger hash = string.hash;

    CGFloat hue = ( hash % 256 / 256.0 );  //  0.0 to 1.0
    CGFloat saturation = ( hash % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from white
    CGFloat brightness = ( hash % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black

    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}

It creates more saturated but bright enough and beautiful colors.

Denis Kutlubaev
  • 15,320
  • 6
  • 84
  • 70