22 Sep 2014

An Objective-C random color generator

If you're uncertain about what color to use for an element in your iOS app, a random (nice) color generator maybe might help.

In fact we can use HSB (hue-saturation-lightness) color model to create a random color generator, also limiting the palette to only the nice colours.


Here's my implementation of such a generator:


+ (UIColor *)randomNiceColor
{
    // This method returns a random color in a range of nice ones,
    // using HSB coordinates.

    // Random hue from 0 to 359 degrees.

    CGFloat hue = (arc4random() % 360) / 359.0f;

    // Random saturation from 0.0 to 1.0

    CGFloat saturation = (float)arc4random() / UINT32_MAX;

    // Random brightness from 0.0 to 1.0

    CGFloat brightness = (float)arc4random() / UINT32_MAX;

    // Limit saturation and brightness to get a nice colors palette.
    // Remove the following 2 lines to generate a color from the full range.

    saturation = saturation < 0.5 ? 0.5 : saturation;
    brightness = brightness < 0.9 ? 0.9 : brightness;

    // Return a random UIColor.

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

Full source code here: https://github.com/mrgradyed/stella-utils