iObjectiveSee

Cocoa and iOS Development

Random UIColor

4 comments

Just a quick tip on this Friday afternoon. I’ve been getting a fair amount of mileage out of this UIColor addition. It’s particularly useful when doing drawing in loops; randomizing the color every iteration can help make it clear what’s happening when and where. Enjoy!

+ (UIColor *)randomColor {
    return [self colorWithRed:((float)rand() / RAND_MAX) 
                        green:((float)rand() / RAND_MAX) 
                         blue:((float)rand() / RAND_MAX) 
                        alpha:1.0f];
}

Written by Joe

February 10th, 2012 at 8:30 pm

Posted in Uncategorized

Tagged with , ,

4 Responses to 'Random UIColor'

Subscribe to comments with RSS or TrackBack to 'Random UIColor'.

  1. Just getting into categories – how would this be implemented?

    malaki1974

    1 Aug 12 at 1:00 pm

  2. Good question. To add a category to a class, you need to create .h and .m files for the category — the naming convention is ClassName+CategoryName.h, so for this you might create files called UIColor+iOSeeAdditions.h and .m. In this case, your .h file should name the class with the category name in parentheses, like so:


    #import <UIKit/UIKit.h>

    @interface UIColor (iOSeeAdditions)

    + (UIColor *)randomColor;

    @end

    Then, put the implementation as described in the post in your .m. Be sure to import the header file to avoid compiler warnings when calling your category methods.

    Joe

    1 Aug 12 at 2:06 pm

  3. I like using this so that you can get a random colour but still control the alpha

    +(UIColor *)randomColorWithAlpha:(const float)alpha {

    return [UIColor colorWithRed:((float)rand() / RAND_MAX)
    green:((float)rand() / RAND_MAX)
    blue:((float)rand() / RAND_MAX)
    alpha:alpha];
    }

    robm

    17 Jan 13 at 7:53 am

  4. Great point, it’s definitely nice to have control of the alpha.

    You should pull the git repo and submit a pull request

    Sarah

    19 Jan 13 at 4:00 pm

Leave a Reply