Search code examples
iosobjective-cuicolorarc4random

Randomly Generate A Color Similar To Another Color


In my app, I randomly generate a color via the following function:

UIColor *origionalRandomColor = [UIColor
                                   colorWithRed:arc4random_uniform(255) / 255.0
                                   green:arc4random_uniform(255) / 255.0
                                   blue:arc4random_uniform(255) / 255.0
                                   alpha:1.0];

And I want to generate a similar color to the above that is also random. I want to use a constant to determine how similar the new color is to the old color.

I've been trying to do this by first taking the red value, generating a small random number, and randomly choose to add or subtract it to form a new color. Then repeating the process for green and blue. And then I can reassemble the new similar color.

In the following code, counter is an int. When counter is a 1, I want the difference to be more pronounced than it is when counter is 20 for example.

I'm trying to do it like this:

CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha =0.0;
[origionalRandomColor getRed:&red green:&green blue:&blue alpha:&alpha];


//Randomly generates a 0 or 1
//0 results in subtracting - 1 results in adding the value
int AddSubtract = arc4random() %2;

//    double val = 20 - couter;
//    val = val/10 - 1;
//    if (val < .2) {
//        val = .2;
//    }

//    float x = (arc4random() % 100)/(float)100;
//    NSLog(@"**********%f", x);
//    x = x/((float)counter/100);
//    NSLog(@"----------%f", x);

float x = (20-counter)/10;
NSLog(@"----------%f", x);


if (AddSubtract == 0)   //subtract the val
    red -= x;
else                    //add the val
    red += x;

//Then repeated for green/blue

UIColor *newColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];

The problem I'm having with the above is it that it is generating new colors that are drastically different than the original color. The original color will be a shade of green, and the new color will be a bright purple. When I NSLog the values, I'm getting crazy numbers, so clearly something is going awry.

Thanks in advance!


Solution

  • You have

    float x = (20-counter)/10;
    

    Given counter is an int, (20-counter)/10 can only be 0, 1 or 2. You have to add a type-cast:

    float x = (float)(20-counter) / 10;
    

    or easier

    float x = (20f - counter) / 10f;