Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C UIColor to NSString

I need to convert a UIColor to an NSString with the name of the color i.e.

[UIColor redColor];

should become

@"RedColor"

I've already tried[UIColor redColor].CIColor.stringRepresentation but it causes a compiler error

like image 903
Alex Avatar asked Dec 15 '12 20:12

Alex


2 Answers

Just expanding on the answer that @Luke linked to which creates a CGColorRef to pass to CIColor:

CGColorRef colorRef = [UIColor grayColor].CGColor;  

You could instead simply pass the CGColor property of the UIColor you're working on like:

NSString *colorString = [[CIColor colorWithCGColor:[[UIColor redColor] CGColor]] stringRepresentation];

Don't forget to import the Core Image framework.

Side note, a quick and easy way to convert back to a UIColor from the string could be something like this:

NSArray *parts = [colorString componentsSeparatedByString:@" "];
UIColor *colorFromString = [UIColor colorWithRed:[parts[0] floatValue] green:[parts[1] floatValue] blue:[parts[2] floatValue] alpha:[parts[3] floatValue]];
like image 149
Mick MacCallum Avatar answered Nov 12 '22 13:11

Mick MacCallum


This is the shortest way to convert UIColor to NSString:

- (NSString *)stringFromColor:(UIColor *)color
{
    const size_t totalComponents = CGColorGetNumberOfComponents(color.CGColor);
    const CGFloat * components = CGColorGetComponents(color.CGColor);
    return [NSString stringWithFormat:@"#%02X%02X%02X",
            (int)(255 * components[MIN(0,totalComponents-2)]),
            (int)(255 * components[MIN(1,totalComponents-2)]),
            (int)(255 * components[MIN(2,totalComponents-2)])];
}
like image 32
k06a Avatar answered Nov 12 '22 14:11

k06a