22 Sep 2014

An Objective-C random gradient generator

Using the random color generator presented in a previous post, we can create a random gradient generator for using in our iOS apps.

We can make a class method that take no arguments and returns a 3-color CAGradientLayer, that we could apply as a nice background for our UIView(s) with just one line of code:
[self.view.layer insertSublayer:[ColorUtilities randomGradient] atIndex:0];

Here's my implementation of a random gradient generator:

+ (CAGradientLayer *)randomGradient
    // This method provides a nice 3-colors random gradient.

    // Get 3 random colors.

    UIColor *startColor = [ColorUtilities randomNiceColor];
    UIColor *middleColor = [ColorUtilities randomNiceColor];
    UIColor *endColor = [ColorUtilities randomNiceColor];

    // Create a CAGradientLayer object.

    CAGradientLayer *gradientLayer = [CAGradientLayer layer];

    // Set the gradient's colors to be the random ones above, using an array of
    // CGColors.

    gradientLayer.colors =
        @[(id)startColor.CGColor, (id)middleColor.CGColor, (id)endColor.CGColor];

    // Set the gradient colors' locations.

    gradientLayer.locations = @[ @(0.0f), @(0.5f), @(1.0f) ];

    // The gradient will be a background gradient, covering its whole frame.

    gradientLayer.startPoint = CGPointMake(0.0f, 0.0f);
    gradientLayer.endPoint = CGPointMake(1.0f, 1.0f);

    // Return this random gradient layer.

    return gradientLayer;

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